When Constructors Are Called

In a class hierarchy, constructors are called in order of derivation, from superclass to subclass.

The following program illustrates when constructors are executed:

 
class A {
  A() {
    System.out.println("Inside A's constructor.");
  }
}

// Create a subclass by extending class A.
class B extends A {
  B() {
    System.out.println("Inside B's constructor.");
  }
}

// Create another subclass by extending B.
class C extends B {
  C() {
    System.out.println("Inside C's constructor.");
  }
}

public class Main{
  public static void main(String args[]) {
    C c = new C();
  }
}

The output from this program is shown here:


Inside A's constructor.
Inside B's constructor.
Inside C's constructor.
Home 
  Java Book 
    Class  

Inheritance:
  1. Inheritance Basics
  2. When Constructors Are Called
  3. Using super keyword
  4. What is Method Overriding
  5. super and overridden method
  6. Method overriding vs method overload
  7. Dynamic Method Dispatch
  8. final variables