Hierarchical Inheritance in java
Java Programming Language / Class, Object and Methods in java
4014
Program:
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.
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.