what is hierarchical inheritance in java with example
Hierarchical inheritance in Java refers to a scenario where a single superclass (parent class) is inherited by multiple subclasses (child classes). Each subclass may further act as a superclass for other classes. This creates a hierarchical structure or tree-like arrangement of classes. The advantage of hierarchical inheritance is that it allows for the sharing of common features among multiple classes while still enabling specialization in each branch of the hierarchy.
Here’s an example of hierarchical inheritance in Java:
// Superclass (Parent class)
class Animal {
void eat() {
System.out.println("Animal is eating.");
}
void sleep() {
System.out.println("Animal is sleeping.");
}
}
// First subclass (Child class 1) inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking.");
}
}
// Second subclass (Child class 2) inheriting from Animal
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing.");
}
}
// Third subclass (Child class 3) inheriting from Animal
class Elephant extends Animal {
void trumpet() {
System.out.println("Elephant is trumpeting.");
}
}
public class Main {
public static void main(String[] args) {
// Creating instances of the subclasses
Dog myDog = new Dog();
Cat myCat = new Cat();
Elephant myElephant = new Elephant();
// Accessing methods from the superclass and subclasses
myDog.eat(); // Inherited from Animal
myDog.sleep(); // Inherited from Animal
myDog.bark(); // Specific to Dog
System.out.println(); // Separating output for clarity
myCat.eat(); // Inherited from Animal
myCat.sleep(); // Inherited from Animal
myCat.meow(); // Specific to Cat
System.out.println(); // Separating output for clarity
myElephant.eat(); // Inherited from Animal
myElephant.sleep(); // Inherited from Animal
myElephant.trumpet(); // Specific to Elephant
}
}
In this example:
Animal
is the superclass (parent class) with methodseat()
andsleep()
.Dog
,Cat
, andElephant
are subclasses (child classes) that inherit from theAnimal
class.- Each subclass adds its own specific behavior (
bark()
,meow()
, andtrumpet()
, respectively) while inheriting common behavior from the superclass. - The
main
method demonstrates creating instances of each subclass and calling methods from both the superclass and the subclasses.
This structure forms a hierarchy where Animal
is the common ancestor, and Dog
, Cat
, and Elephant
are branches of the hierarchy inheriting from the common superclass.