When Constructors are Called?



 Constructors is always called from super class to sub classes.


 super() execute very first statement of constructor in a subclass  and this order is same.


If super() is not used default constructor is execute of all super class.


// See constructors are called.

// Create super class.

class X {
  X() {
    System.out.println("Inside X constructor.");
  }
}


// Create a subclass by extending class X.

class Y extends X {
  Y() {
    System.out.println("Inside Y constructor.");
  }
}


// Create another subclass by extending Y.

class Z extends Y {
  Z() {
    System.out.println("Inside Z constructor.");
  }
}
 
class CallingConstructor {
  public static void main(String args[]) {
    Z z = new Z();
  }
}


Output:

Inside X constructor.
Inside Y constructor.
Inside Z constructor

Comments

Popular posts from this blog

Inheritance in Java

Operators in Java Language?

Type Casting or Conversion in Java