【翻译】Abstract Classes Have Constructors

1) In Java , we have default constructors provided for classes by the compiler (in case one is not declared).

2) The abstract classes can't be instantiated by using the new operator because they don't provide full implementation of all the methods.

Then does it make sense to have constructors inside abstract classes. Let us find it using a sample abstract class:


public abstract class Test{
public abstract void doSomething();
}

The decompiled code for this class will show the truth about constructors in abstract classes in Java


public abstract class Test
{
public Test()
{
}
public abstract void doSomething();
}


Woha!! that constructor was provided by Java. Why?

The reason is that when a class extends any other class and an instance of the subclass is created then the constructor calls are chained and the super class constructors are invoked. This rule is no exception for abstract class

Moreover, having constructors in a class doesn't necessarily mean that instance of that class will be created using the new operator, but the constructors are intended for writing any initializing code.
总而言之,有构造函数的类不见得就能用new操作符来实例化
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值