如果你有一个构造函数,在调用super()时调用this(),那么this()会在第一个被调用的构造函数中执行吗?还是在最后一个没有使用this()关键字的构造函数中执行?
主函数调用:new B()
在这个例子中,输出是"A B1 B0"。但对我而言不清楚super()构造函数是在选项1还是选项2中被调用(因为在这种情况下输出结果相同)。
主函数调用:new B()
public class A {
public A(){
System.out.print("A ");
}
}
public class B extends A {
public B(){
// is super called here? Option 1
this(1);
System.out.print("B0 ");
}
public B(int i){
// or is super called here? Option 2
System.out.print("B1 ");
}
}
在这个例子中,输出是"A B1 B0"。但对我而言不清楚super()构造函数是在选项1还是选项2中被调用(因为在这种情况下输出结果相同)。
B()
调用B(int)
(使用this(1)
),因此它不会调用 super。B(int)
没有显式的构造函数调用,因此编译器会生成对super()
的调用。 - Mark Rotteveel