Menu
Topics Index
...
`

Method Overriding Multiple Levels - Java Example Program


Method Overriding Multiple Levels
class MultiLevelMethodOverriding
{
    public static void main(String arg[])
    {
        System.out.println("----------------------------");
        A a = new A();
        a.print();
        System.out.println("----------------------------");
        B b = new B();
        b.print();
        System.out.println("----------------------------");
        C c = new C();
        c.print();
        System.out.println("----------------------------");
        D d = new D();
        d.print();
        System.out.println("----------------------------");
        E e = new E();
        e.print();
        System.out.println("----------------------------");    
    }
}

class A
{
    void print()
    {
        System.out.println("In class A");
    }
}

class B extends A
{
    void print()
    {
        super.print();
        System.out.println("In class B");
    }
}

class C extends B
{
    void print()
    {
        super.print();
        System.out.println("In class C");
    }
}

class D extends A
{
    void print()
    {
        System.out.println("In class D, printing before super class A");
        super.print();
    }
}

class E extends A
{
    void print()
    {
        System.out.println("In class E, not calling the super class method at all.");
    }
}
OUTPUT

----------------------------
In class A
----------------------------
In class A
In class B
----------------------------
In class A
In class B
In class C
----------------------------
In class D, printing before super class A
In class A
----------------------------
In class E, not calling the super class method at all.
----------------------------

DESCRIPTION

Here we have created five classes A, B, C, D and E. B extends from A, C extends from B, D extends from A, E extends from A. We have implemented the print method in all the classes. In class B and class C, we are calling the super class method before printing, where as in class D, we are printing before calling the super class method. In class E, we are not calling the super-class method at all.

THINGS TO TRY
  • Create one more class F which extends from class C and implement in the print method. Call the super-class print method using super.print() before printing "In class F" in that method.
  • Create one more class G which extends from class A and implement in the print method. Call the super-class print method using super.print() both before and after printing the statement "In class G". Observe that there is no limitation on the number of times we can call the super-class method in the sub-class method.

© meritcampus 2019

All Rights Reserved.

Open In App