new A(){} 原理,new对象时加{}有什么用

这篇博客探讨了如何在Java中创建匿名子类来调用受保护构造器的情况。由于A类的构造器是受保护的,不能直接通过new A()创建实例,但可以通过创建一个匿名子类并在其内部调用super()来实现。博客详细解释了这个过程,包括匿名子类默认构造器的生成、默认构造器的公共可见性和调用父类构造器的步骤。
摘要由CSDN通过智能技术生成
A a = new A(){};

生成一个匿名的子类实现,因为A中的构造器是

protected

不能直接new但是子类可以调用;

public class B extends A{
    B (){
       super();
    }
}

Here’s what happens when that line is executed:

An anonymous subclass of SomeClass is created.
That anonymous subclass is given a default no-argument constructor, just like any other Java class that is declared without a no-argument constructor.
The default no-argument constructor is defined with visibility public
The default no-argument constructor is defined to call super() (which is what no-arg constructors always do first).
The new command calls the no-argument constructor of this anonymous subclass and assigns the result to a

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值