Friday, 25 November 2016

Program to demonstrate the constructor calling order

Constructor is a special type of method which enables to initialize an object when it is first created. It has the same name as the class name in which it is declared. It does not specify a return type not even void. Constructor may be default constructor or paramerized constructor. It has following syntax:
// Default constructor
<class-name> ( ) {
    // Statements


// Parameterized constructor
<class-name> (parameter list) {
    // Statements

When the class hierarchy in multilevel inheritance is created, there is a sequence in which the default constructors are called. Constructors are always called in the order of derivation from super class to subclass. This order does not change though the ‘super ( )’ is used or not used. If super ( ) is not used, then the default constructor of each super class will be executed. In below program when you will create an object of C then the A's constructor is invoked first then B's constructor and finally the C's constructor is called.

//The constructors are called in order of derivation.
//Create a super class.
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 ConstructorCallingSeq {

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

C:\>java ConstructorCallingSeq
Inside A's constructor.
Inside B's constructor.
Inside C's constructor.

No comments:

Post a Comment