class B {
{
System.out.println("IIB B");
}
B(int i) {
System.out.println("Cons B int");
}
public B() {
this(10);
System.out.println("Cons B");
}
}
public class C extends B {
{
System.out.println("IIB C");
}
public C() {
System.out.println("Cons C");
}
public static void main(String[] args) {
C c1 = new C();
}
}
输出
IIB B
Cons B int
Cons B
IIB C
Cons C
根据Oracle教程,Java编译器会将初始化块复制到每个构造函数中。因此,这种方法可用于在多个构造函数之间共享代码块。
那么为什么B类的初始化块不会随着构造函数执行两次而执行两次呢?