Problem description
The following piece of code which is taken from OCA/OCP Java SE 7 Programmer I & II Study Guide produces the following output:
r1 r4 pre b1 b2 r3 r2 hawk
My Solution which was wrong: pre r1 r4 b1 b2 r3 r2 hawk
.
This is the logic that I followed:
First we start by printing
pre
which is before the instantiation ofhawk()
What is in the
static
blocks will be printed first:r1 r4
- From the base class
Bird
we print what is in the block then what is in the constructor :b1, b2
- We move on to the first subclass
Raptor
and we printr3, r2
- Finally we print
hawk
which is in classHawk
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 ");
}
}
Explanation of the solution which is provided by the book
Static init blocks are executed at class loading time; instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down.
Questions
- Static init blocks are executed at class loading time: It's also the class loading time of Hawk right? When class hawk is loaded it will automatically go up the inheritance tree? Even before printing
pre
. - Why isn't the solution :
r1 r4 b1 b2 r3 r2 pre hawk
- It's like it went all the way up the inheritance to print what is in the
static
methods then came all the way down to printpre
. Then it went all the way up again to print what the in theblocks
andconstructors
. Then finally printed hawk.
It's a little confusing for me. Sorry If I butchered the java language.