Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Constructors Execution Order

Constructors always execute from top to down that is from superclass to subclass.
Suppose there is a hierarchy of classes X, Y and Z.

Let X be the superclass of Y and Y be the superclass of Z.

Java Programming Language Constructor Execution Order

Here, the constructor of class X will execute first, then the constructor of class Y and at last the constructor of class Z.

Example

class X 
{
    X()
    {
        System.out.println("Constructor X executed");
    }
}

class Y extends X
{
    Y()
    {
        System.out.println("Constructor Y executed");
    }
}

class Z extends Y
{
    Z()
    {
        System.out.println("Constructor Z executed");
    }
}

class ConstructorExeOrder 
{
    public static void main(String args[])
    {
        Z zz = new Z();
    }
}

Output

Constructor X executed
Constructor Y executed
Constructor Z executed

Now we hope you have understood why super() must be used at the starting of the subclass constructor.

The parameterless constructor of the each superclass is executed in two conditions:
1) If super() is not used in a subclass’ constructor (Same as above program).
2) If super() without arguments is used in a subclass’ constructor.

Example

class X 
{
    X()
    {
        System.out.println("Constructor X executed");
    }
}

class Y extends X
{
    Y()
    {
        super();
        System.out.println("Constructor Y executed");
    }
} 

 class Z extends Y
 {
     Z()
     { 
         super();
         System.out.println("Constructor Z executed");
     }
 }

class ConstructorExeOrder2 
{
    public static void main(String args[])
    {
        Z zz = new Z();
    }
}

Output

Constructor X executed
Constructor Y executed
Constructor Z executed

 

Leave a reply