Thursday 14 May 2015

Static control flow in Parent and Child relationship

In my previous article I discussed about static control flow in a class  and let see what will happen when a class loads into JVM on static members with parent & child relationship.

JVM follows below steps to read static members in a class.

1. Identification of static members form Parent to Child.
2. Execution of static variables assignment and static blocks from Parent to Child.
3.Execution of child main() method.


Output:
0
parent static block
0
child static block
child second static block
2
child main() method......

I know the above program is bit confusing, I will try to elaborate more

At first all static members of the class are identified form Parent to Child(just identified , no assignment of variables and execution of static blocks is done), observe [1] to [11] .

After identification variable assignment and execution of static blocks starts from Parent to Child so value 10 is assigned to int firstNumber[12] , the next static block is executed here firstMethod() method is called ,  observe  firstMethod() is trying to print secondNumber which is not yet initialized so the default value “0” is printed,
now control flows back to static block and the next statement  “parent static block”[15] is displayed on console. After the secondNumber is initialized[16] then numberOne is initilaized[17], the next static block is executed here secondMethod() method is called ,  observe  secondMethod() is trying to print numberTwo which is not yet initialized so the default value “0” is printed, now control flows back to static block and the next statement  “child static block”[20] is displayed on console.

After it the second static block is executed and “child second static block” is printed[21], now the numberTwo is initialized[22]. Next the child main method is executed [23] to [25].

No comments:

Post a Comment