Home / Programs / Hierarchical Inheritance in java
Programming Example

Hierarchical Inheritance in java

👁 4,080 Views
💻 Practical Program
📘 Step by Step Learning
Hierarchical Inheritance in Java is a type of inheritance hierarchy in which a single superclass has multiple subclasses. In this type of inheritance, the features of the superclass are inherited by the subclasses, and each subclass can have its own unique features as well. The superclass serves as a common base class for all its subclasses, which share some common features. This helps in reducing code redundancy and making the code more organized. The subclasses can further extend the features of the superclass, leading to a more specialized class hierarchy. Hierarchical Inheritance in Java is a powerful feature that allows for a flexible and modular approach to programming.

Information & Algorithm

Hierarchical Inheritance in java

Program Code

 class Animal{
void eat(){System.out.println("eating...");}
}

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

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

class HierarchicalInheritance{
	public static void main(String args[]){
	Cat c=new Cat();
	c.meow();
	c.eat();
	//c.bark();// Error
	}
}

Output

meow...
eating...
Press any key to continue . . .

Explanation

The above code represents Hierarchical Inheritance in Java. In this type of inheritance, multiple classes extend a single parent class. Here, class Animal is the parent class, and Dog and Cat are the child classes that inherit properties and methods from the Animal class.

The class Dog inherits from the Animal class and has an additional method bark(). The class Cat also inherits from the Animal class and has an additional method meow().

In the main method, an object of the Cat class is created and the meow() method is called to print "meow..." on the console. The eat() method of the Animal class is also called using the same object. However, the bark() method cannot be called using the Cat object because it is not defined in the Cat class.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.