Hierarchical inheritance is a type of inheritance in which two or more classes inherit a single parent class. In this, multiple classes acquire properties of the same superclass. The classes that inherit all the attributes or behaviour are known as child classes or subclass or derived classes. The class that is inherited by others is known as a superclass or parent class or base class. For instance, class B, class C, and class D inherit the same class name.
Syntax :
class A { } class B extends A { } class C extends A { }
In order to implement hierarchical inheritance, we need to ensure at least two classes inherit the same parent class.
Program:
public class A { public void display() { System.out.println("I am a method from class A"); } } class B extends A { public void print() { System.out.println("I am a method from class B"); } } class C extends A { public void show() { System.out.println("I am a method from class C"); } } class D extends A { public void outPut() { System.out.println("I am a method from class D"); } public static void main(String[] args) { B objB = new B(); C objC = new C(); D objD = new D(); objB.display(); objC.display(); objD.display(); } }
Output:
I am a method from class A I am a method from class A I am a method from class A
Explanation:
Program:
public class Employee { int baseSalary; Employee(){ this.baseSalary = 50000; } } class TempEmployee extends Employee{ float incrementPercent; TempEmployee(){ this.incrementPercent = 0.1f; } } class PermanentEmployee extends Employee{ float incrementPercent; PermanentEmployee(){ this.incrementPercent = 0.2f; } public static void main(String[] args) { TempEmployee tempEmployee = new TempEmployee(); PermanentEmployee permanentEmployee = new PermanentEmployee(); System.out.println("Total salary of Temporary Employee :: "+ ((tempEmployee.baseSalary * tempEmployee.incrementPercent) + tempEmployee.baseSalary)); System.out.println("Total salary of Permanent Employee :: "+ ((permanentEmployee.baseSalary * permanentEmployee.incrementPercent) + permanentEmployee.baseSalary)); } }
Output:
Total salary of Temporary Employee :: 55000.0 Total salary of Permanent Employee :: 60000.0
Explanation: