Home Java Programming Language / Programs / Hierarchical Inheritance in java
🚀 Programming Example

Hierarchical Inheritance in java

👁 4,082 Views
💻 Practical Program
📘 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
	}
}
                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.