【翻译】Abstract Classes Have Constructors

本文探讨了Java中抽象类的构造函数作用及其必要性。解释了即使抽象类不能被实例化,构造函数仍然存在的原因,并通过示例代码展示了这一特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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操作符来实例化
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值