<分区>
class Bird {
{
System.out.print("b1 ");
}
public Bird() {
System.out.print("b2 ");
}
}
class Raptor extends Bird {
static {
System.out.print("r1 ");
}
public Raptor() {
System.out.print("r2 ");
}
{
System.out.print("r3 ");
}
static {
System.out.print("r4 ");
}
}
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}
我正在准备 Java OCA 考试。上面的代码来 self 正在学习的书。根据答案结果应该是
r1 r4 pre b1 b2 r3 r2 hawk
虽然我希望它是
pre r1 r4 b1 b2 r3 r2 hawk
考虑到这些规则:
- 静态初始化 block 在类首次加载时运行
- 正常的 init block 在所有 super 构造函数运行后立即运行
有人可以一步一步地告诉我这是怎么发生的吗?我可以理解 r1
和 r4
出现在所有内容之前,但为什么 pre
紧随其后?