Java Constructor in hierarchy

Description

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

Example

The following program illustrates when constructors are executed:

 
class A {//from  w  ww .j  ava 2 s  . c om
  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:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures