Menu
Topics Index
...
`

Multi Level Constructors - Java Example Program


Multi Level Constructors
class MultiLevelConstructors
{
    public static void main(String arg[])
    {
        System.out.println("---------------");
        X x = new X(10);
        System.out.println("---------------");
        Y y = new Y(11, 21);
        System.out.println("---------------");
        Z z = new Z(12, 22, 32);
        System.out.println("---------------");
    
    }
}

class X
{
    int i;
    X(int i)
    {
        this.i = i;
        System.out.println("Created X");
    }
}

class Y extends X
{
    int j;
    Y(int i, int j)
    {
        super(i);
        this.j = j;
        System.out.println("Created Y");
    }
}

class Z extends Y
{
    int k;
    Z(int i, int j, int k)
    {
        super(i, j);
        this.k = k;
        System.out.println("Created Z");
    }
}
OUTPUT

---------------
Created X
---------------
Created X
Created Y
---------------
Created X
Created Y
Created Z
---------------

DESCRIPTION

Here we have a created a hierarchy of classes, Z extending Y, which in turn extending from X. When we observe the output we realize that when creating the sub-class object, the super-class constructor is called before the current constructor. So when object of class Y is created both Created X and Created Y are printed. Similarly when the object of class Z is created Created X, Created Y and Created Z are printed.

THINGS TO TRY
  • Create a class W extending from class Z, with member variable int l and a constructor which takes i, j, k, l as parameters. Pass i, j, k as parameters to the super-class (Z) constructor.

© meritcampus 2019

All Rights Reserved.

Open In App