Types of Inheritance in Java

Inheritance is a way by which a class reuses the variables and methods of another class. A sub class can inherit the members of another class in following five different ways.

  • Single Inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance (A kind of Multiple Inheritance)
  • Multi-level Inheritance

But Java doesn’t support each one of them to avoid some ambiguity.


1. Single Inheritance

When a sub class inherits from a single super class and the super class is inherited by a single sub class, it is called single inheritance.

Single Inheritance in Java
Single Inheritance

In the example below class Mango inherits from a single class Fruit and class Fruit is only inherited by the class Mango. (In real life it is different though.)

Output :

 


2. Multiple Inheritance

In multiple inheritance, a sub class inherits members from two or more super classes like in the diagram below.

Multiple Inheritance in Java
Multiple Inheritance

But Java doesn’t support multiple inheritance due to the diamond problem.

THe Diamond Problem in Java


3. Hierarchical Inheritance

In hierarchical inheritance a single super class is inherited by two or more sub classes.

Hierarchical Inheritance in Java
Hierarchical Inheritance in Java

In the example below, a single class Machine is inherited by three sub classes Car, Bus and Bike.

Output :

 


4. Hybrid Inheritance

Hybrid inheritance is a combination of multiple inheritance and multi-level inheritance. Since java doesn’t support multiple inheritance, it won’t support a hybrid inheritance. It happens so, due to the same diamond problem described above.

Hybrid Inheritance is not supported in Java


5. Multi-level Inheritance

In multi-level inheritance, one class is inherited by another class which in turn is inherited by another class.

Multilevel Inheritance in Java

In the example below, the class Animal is inherited by Mammal class which in turn is inherited by the Human class.

 


Notes

  • Once you inherit a class, you can use its variables and methods as if they were defined inside the sub class.
  • If you have same name for variables or methods of sub class and the super class, then the members inside sub class hide the members of super class. But you can always access the super class members by using the super keyword.
  • In real life, you would often mix-up different type of inheritance patterns.