Multiple Inheritance occurs when a class is derived from more than one base class, i.e. when a class has more than one immediate parent class.
For example
1. A Hyundai Elantra IS A Car
2. A Hyundai Elantra IS A Sedan as well
A class in Java cannot extend from more than one class. As a result, the question of “how can we implement multiple inheritances” arises. Interfaces are the answer to the preceding question. Interfaces can be used to implement multiple inheritances in Java. A class may implement multiple interfaces, and an interface may extend from multiple interfaces.
Take the same example mentioned above. That can be implemented using the following.
1. A base class named Car 2. An interface named IsSedan 3. An Elantra class derived from Car and implementing IsSedan
The above illustration then becomes,
Image by Author |
Implementation in Java
The output is
The model of Elantra is: 2019 The manufacturer of Elantra is: Hyundai The variant of Elantra is: Sport The bootspace of Elantra is: 420 litres
The model of Elantra is: 2018
The manufacturer of Elantra is: Hyundai
The variant of Elantra is: Eco
The bootspace of Elantra is: 420 litres
Interface vs Abstract Class
Hope this can help. Share your thoughts too.
Comments
Post a Comment