I don't get it.
So this is the code in the question:
Code: Select all
class Employee {
static int i = 10; {
i = 15;
System.out.print(" Employee "+i);
}
static { System.out.print(" Employee static "+i); }
}
class Manager extends Employee {
static {
i = 45;
System.out.print(" Manager static ");
}{
i = 30;
System.out.print(" Manager "+i);
}
}
class Owner extends Manager{
static { System.out.println("Owner"); }
}
public class TestClass {
public static void main(String[] args) {
Manager m = new Manager();
}
}
The rules I know with regard to the order of execution of instance initialization & static initialization blocks are as follows (from Sierra & Bates' OCA Java SE 7 Programmer I Study Guide, p139):
1) Initialization blocks execute in the order in which they appear
2) Static initialization blocks run once, when the class is first loaded
3) Instance initialization blocks run every time a class instance is created
4) Instance initialization blocks run after the constructor's call to super()
From making the Enthuware questions, I deducted an additional rule:
5) In the execution of code, there is no hierarchical difference between static statments & static initialization blocks, only the order in which they appear matters. The same goes for instance statements & instance initialization blocks, there is no hierarchical difference between them either.
So if I follow the rules, then this is what should be printed:
Manager static Employee static 10 Employee 15 Manager 30.
It should go as follows:
A) new Manager() in the main-method calls the default constructor in the Manager class. Therefore, the Manager-class is loaded and its static initialization block runs (see rule 2). It should print out: "Manager static" .
[Note that this is not a static initialization block so rule 4 doesn't apply.]
B) Then super() is called and class Employee is loaded and its static initialization block runs (rule 2). There is no hierarchical difference in the execution of code between static statements & static initialization blocks (rule 5) [so whichever static statement or static initialization block that appears first, also runs first. So static int i first gets the value 10, and then the static initialization block runs, so it prints out: "Employee static 10".
C) Then super() in Object() gets called and then control comes back to class Employee. Now rule 4 (and 5) go into effect: Instance initialization blocks run after the constructor's call to super(), so the instance initialization block gets printed (and i gets value 15). It prints out: "Employee 15".
D) Then control goes back to the class Manager. Rule 4 (and 5) go into effect): Instance initialization blocks run after the constructor's call to super() so "Manager 30" gets printed.
What am I doing wrong? Please help me understand.