Inheritance in Java

Inheritance is the best feature in Java and one of the OOPs concepts, it helps us to reduce the lines of code and increase the code reusability. It shows IS-A relationship. To achieve inheritance we need at least 2 classes. In that one is called parent class and another one is called child class. There are different types of inheritance. In that Java is not supported the multiple inheritance and hybrid inheritance.

Types of Inheritance

  • Single.
  • Multiple.
  • Multilevel.
  • Hierarchical.
  • Hybrid.

Keywords used for

  • Extends is a keyword to inherit the class or an abstract class to the child class.
  • Implements keyword used to inherit the interface to the child class.

Single inheritance

There will be two classes associated, one class is called parent class and another class is called child class.

single inheritance

Multiple inheritance

There will be more than two classes associated, child class has the two parent classes. Java isn’t supported the multiple inheritance through Java class. But we can achieve multiple inheritance using interfaces.

multiple inheritance

In the first diagram, Class C is a child class that inherits the two parent classes. Java does not support that approach because if class A and B have the same method and class C try to access any one of that method JVM get confused to call the correct method and produce the ambiguity error.

In the second diagram, Class C is the child class that inherits the Class A and Interface B. Java is supporting this approach, it will not produce an ambiguity error.

Multilevel Inheritance

There will be more than two classes involved, each class inherits the another one class.

multilevel inheritance

Hierarchical Inheritance

Hierarchical inheritance represents two child class can have the same parent class.

hierarchical inheritance

Hybrid Inheritance

In simple word you can say hybrid inheritance is a combination of different types of inheritance.

Hybrid Inheritance