Java-Multilevel Inheritance

Multilevel Inheritance

Java supports multilevel hierarchy, it means that, you can build hierarchies that contain as many layers of inheritance as you want. For example, given three class called DataV1,  DataV2 and  DataV3. The class DataV1 serves as a base class for the derived class DataV2 as which in turn serves as a base class for the derived class DataV3. This makes each subclass inherits all of its superclass. So DataV3 has all aspects of  DataV1 and  DataV2.

In the hierarchical inheritance the constructors are called in order of derivation from super class to subclass. If super() is not used then the default constructor of each super class will be executed.

Program

1

Program Source

class DataV1 {
    
    int data1;
    int data2;
    
    DataV1(int d1,int d2)
    {
        data1 = d1;
        data2 = d2;
    }
}

class DataV2 extends DataV1 {
    
    int data3;
    int data4;
    
    DataV2(int d1,int d2,int d3,int d4)
    {
        super(d1,d2);
        data3 = d3;
        data4 = d4;
    }
}

class DataV3 extends DataV2 {
    
    int data5;
    int data6;
    
    DataV3(int d1,int d2,int d3,int d4,int d5,int d6)
    {
        super(d1,d2,d3,d4);
        data5 = d5;
        data6 = d6;
    }
    
    void printValues()
    {
        System.out.println("data1 = "+data1);
        System.out.println("data2 = "+data2);
        System.out.println("data3 = "+data3);
        System.out.println("data4 = "+data4);
        System.out.println("data5 = "+data5);
        System.out.println("data6 = "+data6);
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        DataV3 obj = new DataV3(10,20,30,40,50,60);
        obj.printValues();
    }
}

Leave a Comment