Types of Inheritance
Learn about the various types of inheritance in Java.
We'll cover the following...
Based upon superclasses and subclasses, there are the following five types of inheritance in general:
- Single
- Multi-level
- Hierarchical
- Multiple
- Hybrid
Single Inheritance
In single inheritance, there is only a single class extending from another class. We can take the example of the Vehicle class (Super class) and the Car class (Sub class). Let’s implement these classes below:
Multi-level Inheritance
When a class is derived from such a class which itself is derived from another class, this type of inheritance is called Multilevel Inheritance. Classes can be extended to any further levels as per the requirement of the model.
Let’s implement the three classes illustrated above:
- A
CarIS AVehicle - A
PriusIS ACar
Hierarchical Inheritance
When more than one classes inherit from the same class, it is referred to as hierarchical inheritance. In hierarchical inheritance, more than one classes extend, as per the requirement of the design, from the same base class. The common attributes of these child classes are implemented inside the base class.
Example:
- A
CarIS AVehicle - A
TruckIS AVehicle
Multiple Inheritance
When a class is derived from more than one base class, i.e. when a class has more than one immediate parent classes, this type of inheritance is called Multiple Inheritance.
Example:
- A Hyundai
ElantraIS ACar. - A Hyundai
ElantraIS ASedanalso.
Hybrid Inheritance
A type of inheritance which is a combination of Multiple and Multi-level inheritance is called hybrid inheritance.
- A combustion engine is an engine
- An electric motors engine is an engine
- A Hybrid engine combines both combustion engine and electric motors.
Note: In Java, Multiple and Hybrid inheritance are applicable using interfaces only.