代码:
Parent Class:
public class Parent {
int i = 10;
{
System.out.println(i);
}
public Parent(){
System.out.println("Parent");
}
}
Child Class:
public class Child extends Parent {
int j = 20;
{
System.out.println(j);
}
public Child() {
super();
}
}
Test Class:
public class ConstructorTest {
public static void main(String... args){
Child c = new Child();
}
}
执行流程(我所知道的):
Parent
中实例成员从上到下的标识类(class)。Child
中实例成员从上到下的标识类(class)。- 在
Parent
中从上到下执行实例变量赋值和实例 block 类(class)。 - 执行
Parent
构造函数。 - 在
Child
中从上到下执行实例变量赋值和实例 block 类(class)。 - 执行
Child
构造函数。
输出:
10
Parent
20
我的问题是:在第 6 步中 - 执行 Child
期间构造函数,为什么不使用 super()
再次调用父构造函数 child 的?
那么为什么输出不是:
10
Parent
20
Parent
最佳答案
基本上,super()
行已经在步骤 4 中生效了。只是 super();
是隐式的,通常会被删除。通常,您将显式构造函数链接用于:
- 链接到同一类中的构造函数
- 为构造函数提供参数
尽管它位于子构造函数主体的第一行,但 this()
/super()
语句会在之前执行> 实例初始值设定项。您应该将其视为与构造函数主体的其余部分有些分离。
关于Java:子类构造函数的 super() 如何/何时参与实例流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40585619/