Friday, August 11, 2017

Execution flow of program by JVM- Part 1

Program 1- Execution Flow of a program involving static block, instance block, parent and child Constructor

/*Static block of parent is executed first because it is
loaded first and static blocks are called when the class is loaded.*/

class Parentt {

     /* parent static block called -1st*/
     static {
          System.out.println("Parent static block");
     }

     /* Parent Instance block called prior to
      * child IB once object is created -2nd */
     {
          System.out.println("Parent initialisation  block");
     }

     /*Parent constructor called prior to child constructor
      * once instance block is called - 3rd */
     public Parentt() {
          System.out.println("Parent Constructor");
     }

}

class Childd extends Parentt {

     /* child static block called after parent static block - 1st */
     static {
          System.out.println("Child static block");
     }

     /* Instance block called once object is created -2nd */
     {
          System.out.println("Child initialisation block");
     }
    
     /*Child constructor called once instance block is called - 3rd*/
     public Childd() {
          System.out.println("Child Constructor");
     }
}

public class ExecutionFlow {
     /* S(static blocks) -I(Instance Blocks) -Constructors */
     public static void main(String[] args) {
          new Childd();
     }
}

Output

Parent static block
Child static block
Parent initialization block
Parent Constructor
Child initialization block
Child Constructor


No comments:

Post a Comment