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

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

问题描述

为什么Java中的abstract类有一个constructor?

Why does an abstract class in Java have a constructor?

它在构造什么,因为我们不能实例化一个 abstract 类?

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

有什么想法吗?

推荐答案

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

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

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

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.

如果你什么都不做,就会调用父级的默认构造函数.但是,您可以使用 super 关键字来调用父类上的特定构造函数.

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天全站免登陆