Hierarchical inheritance in Java is a type of inheritance in which multiple subclasses inherit from a single superclass. This means that the structure forms a hierarchy, with the superclass at the top and multiple subclasses at the lower levels. Hierarchical inheritance helps in code reusability and logical representation of real-world relationships.
Here's a detailed explanation with an example and its output in Java:
Example of Hierarchical Inheritance in Java
Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
Subclass 1
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
Subclass 2
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
Subclass 3
class Bird extends Animal {
void chirp() {
System.out.println("The bird chirps.");
}
}
Main Class to Test Hierarchical Inheritance
public class Main {
public static void main(String[] args) {
// Create objects for each subclass
Dog dog = new Dog();
Cat cat = new Cat();
Bird bird = new Bird();
// Call methods on Dog object
System.out.println("Dog:");
dog.eat(); // Inherited method
dog.bark(); // Subclass method
// Call methods on Cat object
System.out.println("Cat:");
cat.eat(); // Inherited method
cat.meow(); // Subclass method
// Call methods on Bird object
System.out.println("Bird:");
bird.eat(); // Inherited method
bird.chirp(); // Subclass method
}
}
Output
Dog:
This animal eats food.
The dog barks.
Cat:
This animal eats food.
The cat meows.
Bird:
This animal eats food.
The bird chirps.
Explanation
Superclass
Animal
:- Contains a method
eat()
that prints a message indicating that the animal eats food.
- Contains a method
Subclass
Dog
:- Inherits from
Animal
. - Contains an additional method
bark()
that prints a message indicating that the dog barks.
- Inherits from
Subclass
Cat
:- Inherits from
Animal
. - Contains an additional method
meow()
that prints a message indicating that the cat meows.
- Inherits from
Subclass
Bird
:- Inherits from
Animal
. - Contains an additional method
chirp()
that prints a message indicating that the bird chirps.
- Inherits from
Main Class:
- Creates objects for each subclass (
Dog
,Cat
, andBird
). - Calls both the inherited
eat()
method and the specific method of each subclass (bark()
,meow()
, andchirp()
).
- Creates objects for each subclass (
This example demonstrates hierarchical inheritance by showing how multiple subclasses (Dog
, Cat
, and Bird
) can inherit common behavior (eat()
) from a single superclass (Animal
) while also having their own specific behaviors.