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