0
0
JavaConceptBeginner · 3 min read

Hierarchical Inheritance in Java: Explanation and Example

In Java, hierarchical inheritance is a type of inheritance where multiple subclasses inherit from a single parent class. This means one parent class shares its properties and methods with many child classes, allowing code reuse and organization.
⚙️

How It Works

Hierarchical inheritance works like a family tree where one parent has many children. Imagine a parent class as a blueprint for a general concept, and each child class as a specific version of that concept. Each child inherits the features of the parent but can also have its own unique features.

For example, think of a Vehicle as the parent class. Different types of vehicles like Car, Bike, and Truck are child classes that inherit common properties like speed and color from Vehicle, but each can have special features too.

💻

Example

This example shows a parent class Animal and two child classes Dog and Cat that inherit from it. Both children can use the sound() method from Animal and also have their own methods.

java
class Animal {
    void sound() {
        System.out.println("Animals make sounds");
    }
}

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

class Cat extends Animal {
    void meow() {
        System.out.println("Cat meows");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound();
        dog.bark();

        Cat cat = new Cat();
        cat.sound();
        cat.meow();
    }
}
Output
Animals make sounds Dog barks Animals make sounds Cat meows
🎯

When to Use

Use hierarchical inheritance when you have one general class and several specialized classes that share common behavior. It helps avoid repeating code by putting shared features in the parent class.

For example, in a software for a zoo, you might have a general Animal class and specific classes like Lion, Elephant, and Monkey that inherit from it. This keeps your code organized and easier to maintain.

Key Points

  • One parent class with multiple child classes.
  • Child classes inherit common properties and methods from the parent.
  • Each child class can have its own unique features.
  • Helps reuse code and organize related classes.

Key Takeaways

Hierarchical inheritance means many child classes inherit from one parent class.
It promotes code reuse by sharing common features in the parent class.
Each child class can add its own specific behavior.
Use it to organize related classes with shared characteristics.