问题描述
我有以下2个课程
public class classA {
classA() {
System.out.println("A");
}
}
class classB extends classA {
classB() {
System.out.println("B");
}
}
然后运行
classA c = new classB();
或
classB c = new classB();
总是给
A
B
为什么会这样?乍一看,无论哪种情况,我都将假定仅调用classB
构造函数,因此唯一的输出将是
Why is this happening? At first glance, in either scenario, I would assume that only the classB
constructor would be called and thus the only output would be
B
但这显然是错误的.
推荐答案
这就是Java的工作方式.在调用子类的构造函数之前,将通过Object
一直调用父类的构造函数.
That is how Java works. The constructors of the parent classes are called, all the way up the class hierarchy through Object
, before the child class's constructor is called.
引用文档:
如果子类构造函数显式或隐式调用其超类的构造函数,则您可能会认为将调用整个构造函数链,一直返回到Object
的构造函数.实际上就是这种情况.它称为构造函数链接,当类下降很长时,您需要意识到这一点.
If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object
. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.
这篇关于为什么总是调用超类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!