为什么Java中的抽象类有构造函数? [英] Why do abstract classes in Java have constructors?

查看:676
本文介绍了为什么Java中的抽象类有构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Java中的抽象类具有构造函数



它构造什么,因为我们不能实例化抽象类?



任何想法?

解决方案

Java中的构造函数实际上不构建对象,它用于初始化字段。 >

想象你的抽象类有字段x和y,并且你总是希望它们以某种方式初始化,无论最终创建什么实际的子类。所以你创建一个构造函数并初始化这些字段。



现在,如果你有两个不同的子类的抽象类,当你实例化它们的构造函数将被调用,然后父构造函数将被调用,字段将被初始化。



如果你不做任何事情,父类的默认构造函数将被调用。但是,可以使用super关键字来调用父类的特定构造函数。


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.

这篇关于为什么Java中的抽象类有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆