Java Hybrid Inheritance With Example

Hello everyone, In this tutorial, we are going to learn about Hybrid inheritance in Java.

Before diving right into hybrid inheritance let us first quickly look at some other types are inheritance commonly used in Java. As you may know, Java typically uses four types of inheritance:

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance

Single Inheritance: When a class extends another one class we call it Single Inheritance.

Single Inheritance

Here A is called the parent class and B is derived class.

Multilevel Inheritance: When we extend from a derived class making it parent class for some other class it is known as multilevel inheritance.

Multilevel inheritance

Here class A is parent class for class B and class B is parent class for class C.

Hierarchical Inheritance: When a single class has more than one child classes it is known as Hierarchical Inheritance. Manager having more than one employee under him can be an example of Hierarchical Inheritance.

Hierarchical Inheritance

Multiple Inheritance: When a subclass inherits from more than one class it is known as Multiple Inheritance.

Multiple Inheritance

It is easy to represent Multiple Inheritance with the help of a diagram but Multiple Inheritance isn’t supported in Java directly using classes because it may cause Diamond Problem (also known as Deadly Diamond of Death). Multiple Inheritance in Java can be implemented using Interfaces, A single base class will implement two different Interfaces.

Java Hybrid Inheritence

Now coming to Hybrid Inheritance it is evident from the name that it is mixing of two different types of inheritance.

Hybrid Inheritance

Here B is inheriting from A and C so it is an example of Multiple Inheritance and D is inheriting B which is an example of Simple Inheritance so in total we can say that this is an example of Multiple Inheritance.

Here Employee class implements read and work interfaces which is an example of multiple inheritance and HourlyEmployee in turn extends Employee which is an example of Single Inheritance therefore this is an example of Hybrid Inheritance.

When working with complex projects it is generally seen that hybrid inheritance is used more than any other type of inheritance as it gives us flexibility to work with different classes.

Leave a Reply

Your email address will not be published. Required fields are marked *