Java Notes | Abstract class & Multi-level Inheritance

In Java, when you have an abstract class with multiple levels of inheritance, each subsequent child class in the hierarchy is not required to implement all the abstract methods of the abstract superclass. Since, if the intermediate child classes have already provided implementations for the methods, the child classes inherit the implementations from them.

Consider this example,

abstract class AbstractClass {
    abstract void methodA();
}

class ChildClass1 extends AbstractClass {
    void methodA() {
        // Implementation for methodA
    }
}

class ChildClass2 extends ChildClass1 {
    // No implementation for methodA
}

class ChildClass3 extends ChildClass2 {
    // No implementation for methodA
}

In this example, ChildClass1 directly extends AbstractClass and provides an implementation for the abstract method methodA. Therefore, it fulfills the requirement of implementing all abstract methods from its abstract superclass.

ChildClass2 extends ChildClass1 but does not provide any implementation for methodA. Since ChildClass1 has already implemented methodA, ChildClass2 is not required to implement it again.

ChildClass3 directly extends ChildClass2, which in turn extends ChildClass1. Since ChildClass1 has already implemented methodA, ChildClass3 inherit the implementation from ChildClass1.
Therefore, when we create an object of ChildClass3 and invoke methodA, it will call the implementation provided by ChildClass1.

Note:
If ChildClass2 also implements methodA, then ChildClass3 would inherit the implementation from ChildClass2. In Java, when a child class extends another child class and both parent classes provide an implementation for the same method, the child class overrides the implementation of the immediate parent class. You could verify this from here.

In summary, each child class in the hierarchy is responsible for implementing abstract methods that have not been implemented by its superclasses. If an intermediate child class has already provided an implementation, the subsequent child classes are not required to implement it again.

Here’s a working example: Java Abstract Class

Leave a Reply

Your email address will not be published. Required fields are marked *