Friday, August 11, 2017

Execution flow of program by JVM - part 2

Program 2 – Involving static variable initialization, static block ,  instance variable initialization and constructor calling 

class Example {
     public static int step_1 = step(1);   <- CALLED First
     public int step_6 = step(6);

     static {
          step(2);                         <- CALLED Second       
     }

     public Example() {
          step(7);
     }

     // Just for demonstration purposes:
     public static int step(int step) {
          System.out.println("Step " + step);
          return step;
     }
}

public class ExampleSubclass extends Example {
     public static int step_3 = step(3);     <- CALLED THIRD
     public int step_8 = step(8);

     static {
          step(4);                          <- CALLED FOURTH
     }

     public ExampleSubclass() {
          step(9);
     }

     public static void main(String[] args) {
          step(5);
          new ExampleSubclass();
     }
}

Step 1, Step 2, Step 3, Step 4 is called during class loading by JVM before calling step(5)

Static initialization variables -->Static blocks --> Parent constructor invoke instance variable initialization --> Parent constructor invokes --> Child constructor invoke child instance variable initialization --> Child constructor invokes

Note- Static variables and static block of parent class and then child class is invoked at the starting of loading of the classes, even before execution of first line of main()

Output

Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8

Step 9

No comments:

Post a Comment