Java Constructor in hierarchy

In this chapter you will learn:

  1. Java Constructor in hierarchy
  2. When constructors are called when invoking a subclass

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  w w. j a v  a2 s.  com*/
  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:

Next chapter...

What you will learn in the next chapter:

  1. What is Polymorphism
  2. What is dynamic method dispatch
  3. Polymorphism Example