Hierarchical Inheritance in Java

 In Java, hierarchical inheritance is a type of inheritance where a single parent class is inherited by multiple child classes. In this type of inheritance, each child class has its own unique set of properties and methods, in addition to the ones inherited from the parent class.

To create hierarchical inheritance in Java, you need to define a parent class with the common properties and behaviors that you want to inherit, and then create multiple child classes that extend the parent class. The child classes can then add their own specific properties and behaviors as needed.

Here is an example code snippet that demonstrates hierarchical inheritance in Java:

csharp
// Parent class class Animal { public void eat() { System.out.println("I am eating"); } } // Child class 1 class Dog extends Animal { public void bark() { System.out.println("Woof!"); } } // Child class 2 class Cat extends Animal { public void meow() { System.out.println("Meow!"); } } // Usage public static void main(String[] args) { Dog myDog = new Dog(); myDog.eat(); // inherited from Animal class myDog.bark(); // specific to Dog class Cat myCat = new Cat(); myCat.eat(); // inherited from Animal class myCat.meow(); // specific to Cat class }

In this example, the Animal class is the parent class, and Dog and Cat are the child classes that inherit from it. Both child classes have their own specific methods (bark for Dog and meow for Cat), in addition to the eat method inherited from the Animal class.

Comments

Popular posts from this blog

Cryptography API

Java Applet Overview

Vector in Java