0
0
JavaConceptBeginner · 3 min read

What is Multilevel Inheritance in Java: Explanation and Example

In Java, multilevel inheritance is a type of inheritance where a class inherits from a derived class, forming a chain of inheritance. For example, class C inherits from class B, which inherits from class A, allowing C to access members of both B and A.
⚙️

How It Works

Imagine a family tree where a child inherits traits from their parent, and the parent inherits traits from their own parent. In Java, multilevel inheritance works similarly: a class inherits properties and methods from a parent class, and then another class inherits from that child class, creating a chain.

This means the last class in the chain can use features from all the classes above it. It helps organize code by building on existing classes step-by-step, like stacking building blocks where each block adds something new.

💻

Example

This example shows three classes where each inherits from the previous one, demonstrating multilevel inheritance.

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

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

class Puppy extends Dog {
    void weep() {
        System.out.println("The puppy weeps.");
    }
}

public class Main {
    public static void main(String[] args) {
        Puppy myPuppy = new Puppy();
        myPuppy.eat();   // from Animal
        myPuppy.bark();  // from Dog
        myPuppy.weep();  // from Puppy
    }
}
Output
This animal eats food. The dog barks. The puppy weeps.
🎯

When to Use

Use multilevel inheritance when you want to create a clear hierarchy where each class adds more specific features. For example, in a game, you might have a general Character class, then a Player class that inherits from it, and finally a Wizard class that inherits from Player with special magic abilities.

This approach helps keep code organized and reusable, making it easier to add new features without rewriting existing code.

Key Points

  • Multilevel inheritance forms a chain of classes where each inherits from the previous one.
  • The last class can access members of all its ancestor classes.
  • It helps build specialized classes step-by-step.
  • Java supports multilevel inheritance but not multiple inheritance with classes.

Key Takeaways

Multilevel inheritance allows a class to inherit from a derived class, forming a chain.
It helps reuse and extend code by building on existing classes step-by-step.
The most derived class can access methods and fields from all ancestor classes.
Use it to create clear, organized hierarchies in your code.
Java supports multilevel inheritance but avoids multiple inheritance with classes to prevent complexity.