java 抽象构造函数,为什么Java中的抽象类有构造函数?

Java中的抽象类虽然不能实例化,但其构造器用于初始化字段。即使子类实例化时,父类的构造器也会被调用,确保字段按预设方式初始化。即使不指定,也会默认调用父类的无参构造器。通过`super`关键字,可以调用父类的特定构造器。
摘要由CSDN通过智能技术生成

Why does an abstract class in Java have a constructor?

What is it constructing, as we can't instantiate an abstract class?

Any thoughts?

解决方案

A constructor in Java doesn't actually "build" the object, it is used to initialize fields.

Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.

Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.

If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值