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
}
}
meow... eating... Press any key to continue . . .
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.
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.