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 ");
}
}
I'm preparing for Java OCA exam. Above code is from the book I'm studying right now. According to the answer the result should be
r1 r4 pre b1 b2 r3 r2 hawk
while I would expect it to be
pre r1 r4 b1 b2 r3 r2 hawk
taking into consideration these rules:
- Static init blocks run when class is first loaded
- Normal init blocks run right after all super constructors have run
Could someone please show me step by step how this happens? I can understand r1
and r4
to come before everything but why pre
right after them?