Multilevel inheritance means that a class is derived from another class, which is also derived from another class. This forms a chain of inheritance.

Example Code

				
					// Base class (Parent class)
class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

// Derived class (Child class of Animal)
class Mammal extends Animal {
    void walk() {
        System.out.println("This mammal walks.");
    }
}

// Derived class (Child class of Mammal)
class Dog extends Mammal {
    void bark() {
        System.out.println("This dog barks.");
    }
}

// Main class to test multilevel inheritance
public class MultilevelInheritanceExample {
    public static void main(String[] args) {
        Dog dog = new Dog();
        
        // Calling methods from different levels of the inheritance chain
        dog.eat();   // Method from Animal class
        dog.walk();  // Method from Mammal class
        dog.bark();  // Method from Dog class
    }
}

				
			

Explanation

  1. Animal Class: This is the base class with a method ‘eat()‘.
  2. Mammal Class: This class extends ‘Animal‘ and adds a method ‘walk()‘.
  3. Dog Class: This class extends ‘Mammal‘ and adds a method ‘bark()‘.

When an object of the ‘Dog‘ class is created, it can access methods from the ‘Dog‘ class, the ‘Mammal‘ class, and the ‘Animal‘ class because of the inheritance chain.

Output

When the ‘main‘ method is executed, the following output will be produced:

				
					This animal eats food.
This mammal walks.
This dog barks.

				
			

Detailed Execution Flow

  • dog.eat(): Calls the ‘eat()‘ method from the ‘Animal‘ class because ‘Dog‘ indirectly inherits from ‘Animal‘.
  • dog.walk(): Calls the ‘walk()‘ method from the ‘Mammal‘ class because ‘Dog‘ directly inherits from ‘Mammal‘.
  • dog.bark(): Calls the ‘bark()‘ method from the ‘Dog‘ class itself.

Conclusion

This example demonstrates how multilevel inheritance allows a class to inherit methods from multiple levels up the inheritance chain. The ‘Dog‘ class, which is at the bottom of the chain, can use methods from both the ‘Mammal‘ and ‘Animal‘ classes.

Scroll to Top