Write A Program In Java To Demonstrate Hierarchical Inheritance

0

Write A Program In Java To Demonstrate Hierarchical Inheritance.

Write a program in java to demonstrate hierarchical inheritance

Before understanding the program we need to know about the hierarchical inheritance


Hierarchical inheritance is a type of inheritance in Java where multiple sub-classes are derived from a single parent class. In other words, a single parent class is extended by multiple child classes, creating a hierarchy of classes. Each child class inherits all the properties and methods of the parent class.


In hierarchical inheritance, a parent class has two or more child classes that extend the parent class, but the child classes do not inherit from each other. This creates a tree-like structure, where each child class has its own unique set of properties and methods, in addition to the ones inherited from the parent class.


Hierarchical inheritance is useful when we want to create a set of related classes that share some common properties or behaviors, but also have some unique properties or behaviors that differentiate them from each other. By creating a parent class that contains the common properties and behaviors, we can avoid duplicating code in each child class.


Here's a program in java that demonstrate the use of hierarchical inheritance


Program

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

class Cat extends Animal {
    public void meow() {
        System.out.println("The cat is meowing");
    }
}

public class HierarchicalInheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // calling method of parent class
        dog.bark(); // calling method of child class

        Cat cat = new Cat();
        cat.eat(); // calling method of parent class
        cat.meow(); // calling method of child class
    }
}

Output
The animal is eating The dog is barking The animal is eating The cat is meowing

Explanation

In this example, the animal class is the parent class, and the dog and cat classes are the child classes that extend the animal class. The dog and cat classes inherit the eat() method from the animal class.


As we can see, the dog and cat classes both inherit the eat() method from the animal class, and they have their own unique methods bark() and meow() respectively. This is an example of hierarchical inheritance in java.


❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.


Tags

Post a Comment

0Comments
Post a Comment (0)