Java - OOP - Inheritance - Hierarchical

Hierarchical Inheritance is a type of inheritance where a single base class is inherited by multiple derived classes. This means that multiple child classes are derived from a single parent class. Let's take an example to understand Hierarchical Inheritance better.

Consider the following class hierarchy:

class Shape {
   void draw() {
      System.out.println("Drawing Shape");
   }
}

class Circle extends Shape {
   void draw() {
      System.out.println("Drawing Circle");
   }
}

class Square extends Shape {
   void draw() {
      System.out.println("Drawing Square");
   }
}

In this example, the Shape class is the parent class or the base class, and the Circle and Square classes are child classes or derived classes.

The Circle and Square classes inherit the draw() method from the Shape class. However, both Circle and Square classes have their own implementation of the draw() method. This is an example of Hierarchical Inheritance, where multiple child classes inherit from a single parent class.

Let's see how we can use this class hierarchy in our program:

public class Test {
   public static void main(String args[]) {
      Shape s1 = new Circle();
      s1.draw();

      Shape s2 = new Square();
      s2.draw();
   }
}

In the above code, we create two Shape objects, s1 and s2. s1 is a Circle object, and s2 is a Square object. Both s1 and s2 are assigned to the Shape class reference variables.

When we call the draw() method using the Shape class reference variables, the appropriate draw() method of the derived classes will be called, i.e., the draw() method of Circle will be called for s1, and the draw() method of Square will be called for s2.

The output of the above code will be:

Drawing Circle
Drawing Square

This is because we have overridden the draw() method in the Circle and Square classes, and each child class has its own implementation of the draw() method.