Once a class is loaded in memory its static block and static members are first inialized and executed. So when JVM invokes main() of child Child.main(), First Child methods static block and static variables are initialized but since Child class does not have both nothing happens and since Child class extends Parent class, Parent class is loaded in memory and static block and static variables are initialized;
First the parent class is loaded in memory and 1) Parent class static block is executed first 2) Static variables in class are initialized So now the first statement to exceute is: O/P1: "Parent Class Instance Initializer" Now the parent class static memeber is intialized static int bb = getAA(); So the second statement to be executed is the getAA() which displays O/P2: "Parent Class Member Initializer:static" 3) In child class main() if statement is executed which results in true and hence System.out.println("trim"); O/P 3: trim 4)Second if statemen runs and displays "toppercase" O/P 4: toppercase 5) Now Child c = new Child() Now this will first invoke Child() which invokes Parent() through a implicit super() in Child() as the first statement, So now once in Parent() all the instance blocks and instance variables are executed and initalized , So now the parent class a=getA() is invoked which displays and there is no instance blocks O/P5: "Parent Class Member Initializer" And onnce the members are initalized the statments in Parent() is executed which is "Parent Class Constructor" O/P 6: "Parent Class Constructor" And it returns to Child class, Again same logic as above is applied O/P 7 : "Child Class Instance Initializer" O/P 8: "Child Class Member Initializer" O/P 9: "Child Class Constructor"
An instance block is for code that shall be the same for all constructors. It will be executed after the call for super but before the rest of the constructor runs.
When you have overloaded constructors, then you could put the code to be shared into the instance block. Example: prints: fish constructor Instance Block providing Nemo with 3 stripes. nemo constructor with int nemo constructor parameterless Nemo with 6 fins and 3 stripes. fish constructor Instance Block providing Nemo with 3 stripes. nemo constructor with int Nemo with 7 fins and 3 stripes.
The two constructors share the instance block, so every Nemo got 3 stripes and we get an output of this.
all events occur in real time
Too many men are afraid of being fools - Henry Ford. Foolish tiny ad: