Hierarchical Inheritance

Hierarchical Inheritance


class A {
    int a;
    A() {
        a = 0;
    }
    A(int x) {
        a = x;
    }
    void display() {
        System.out.println("\na = " + a);
    }
}
class B extends A {
    int b;
    B() {
        super(); // Calling class A - Default Constructor
        b = 0;
    }
    B(int x, int y) {
        super(x); // Calling class A - Parameterised Constructor
        b = y;
    }
    void display() {
        super.display(); // Calling class A - Display method
        System.out.println("b = " + b);
    }
}
class C extends A {
    int c;
    C() {
        super(); // Calling class A - Default Constructor
        c = 0;
    }
    C(int x, int y) {
        super(x); // Calling class A - Parameterised Constructor
        c = y;
    }
    void display() {
        super.display(); // Calling class A - Display method
        System.out.println("c = " + c);
    }
}
class D extends A {
    int d;
    D() {
        super(); // Calling class A - Default Constructor
        d = 0;
    }
    D(int x, int y) {
        super(x); // Calling class A - Parameterised Constructor
        d = y;
    }
    void display() {
        super.display(); // Calling class A - Display method
        System.out.println("d = " + d);
    }
}
class HierarchicalInheritance {
    public static void main(String[] args) {
        // Declaring Variables
        B b, b1;
        C c, c1;
        D d, d1;
        b = new B();
        b1 = new B(1, 2);
        c = new C();
        c1 = new C(3, 4);
        d = new D();
        d1 = new D(5, 6);
        // Calling Display method
        b.display();
        b1.display();
        c.display();
        c1.display();
        d.display();
        d1.display();
    }
}



OUTPUT::


a = 0
b = 0

a = 1
b = 2

a = 0
c = 0

a = 3
c = 4

a = 0
d = 0

a = 5
d = 6

Previous Post Next Post