我有以下两门课
public class classA {
classA() {
System.out.println("A");
}
}
class classB extends classA {
classB() {
System.out.println("B");
}
}
然后运行
1
classA c = new classB();
或
2
classB c = new classB();
总是给予
A
B
为什么会这样?乍一看,在任何一种情况下,我都会假设只有 classB
构造函数会被调用,因此唯一的输出是
B
但这显然是错误的。
最佳答案
这就是 Java 的工作原理。在调用子类的构造函数之前,调用父类的构造函数,通过 Object
一直向上到类层次结构。
引自 the docs :
With
super()
, the superclass no-argument constructor is called. Withsuper(parameter list)
, the superclass constructor with a matching parameter list is called.Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Object
does have such a constructor, so ifObject
is the only superclass, there is no problem.如果子类构造函数显式或隐式调用其父类(super class)的构造函数,您可能会认为将调用整个构造函数链,一直到
Object
的构造函数。事实上,情况就是这样。它被称为构造函数链接,当有很长的类下降时你需要注意它。
关于java - 为什么总是调用父类(super class)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34488484/