I am fairly new to the core concepts of Java and don't have much expertise as to how the execution steps are followed. The following is a code from Kathy & Sierra's book and I am unable to understand how the execution is carried out.
=========
JAVA CODE
=========
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 ");
}
}
Output:
r1 r4 pre b1 b2 r3 r2 hawk
=====================
Help me clarify some doubts
=====================
1. I was under the impression that execution of any code starts from main(). Is that true?
- if it is, then how come the code actually jumps to the class and accesses the static initializer blocks when there is no code accessing the class itself.
2. According to me, the order of execution is like this:
main() --> SOP("pre") --> "pre" is printed on screen --> new Hawk() --> //Raptor is accessed ---> //Bird is accessed --> // r1 and r2 printed ---> r1 r4 r3 r2 printed ---> SOP("Hawk") ---> hawk printed.
Please help me correct the order of execution.
