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.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.