Instance Control flow in Parent to child relationship - rahul00773/JavaConcepts GitHub Wiki

Whenever we are creating child class object the following sequence of events will be performed automatically as a part of instance control flow

  1. Identification of instance members from parent to child
  2. Execution of Instance variable assignments and instance blocks only in the parent class.
  3. Execution of parent constructor.
  4. Execution of Instance variable assignments and instance blocks only in Child class.
  5. Execution of Child constructor.

public class Parent {

int i =10;

{

    m1();
    System.out.println("First Instance method");
}

Parent(){

    System.out.println("Constructor");
}

public static void main(String[] args){
    Parent parent = new Parent();
    System.out.println("Main");
    
}
public void m1()
{

  System.out.println(j);
}



int j =20;

}

public class Child extends Parent {

int x =100;

{
    m2();
    System.out.println("child class first instance block");
}

Child(){

    System.out.println("child constructor");
}

public static void main(String[] args){

    Child child = new Child();

System.out.println("child main");

}

public void m2(){

    System.out.println(y);
}

{
    System.out.println("Second child Instance block");

}
int y=200;

}

Note: From a static area, we can’t access instant members directly. Because while executing static area JVM may not identify instance members.

class Test{

int x =10;

public static void main(String[] args){

System.out.println(x); // Compile time error : non static variable x cannot be referenced from a static context

}

}