Multiple Inheritance Using Interfaces
- Eclipse: Oxygen
- Java: 1.8
Types of Inheritance
In Java, there are 5 types of inheritance namely:
- Single inheritance: One class extends to another class(only one class) is called Single inheritance.
- Multiple inheritance: If one class extending more than one class is called Multiple inheritance. Java does not allow multiple inheritance directly through the class. For example: Class C extends Class A and Class B both.
Note: To make use of this inheritance we need to implement the Interface concept. - Hybrid inheritance: Â A combination of Single and Multiple inheritance is called Hybrid inheritance. This inheritance is also not supported by Java.
- Multilevel inheritance: In Multilevel inheritance, if one class can inherit properties from a derived class. Hence, the derived class becomes the base class for the new class.
- Hierarchical inheritance: If one base class property is inherited by several subclasses it is known as Hierarchical inheritance.
In Java, Single, Multilevel and Hierarchical inheritances are only used .
Note: Out of these only three types of inheritance is possible in Java. Multiple and Hybrid inheritance isn’t supported by Java.
Interfaces, as we discussed earlier, is the outline or the prototype for the classes implementing it. Multiple Inheritance is not allowed in Java due to problems such as the diamond problem which causes crashing of applications.
Interfaces are used to perform multiple inheritances which can be seen in the following example.
As we see, in the project we have multiple interfaces which are implemented by Person class because multiple inheritance does not create any ambiguity in interfaces.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public abstract class Person implements IsAlive, LiveLife{ public void speak() { System.out.println("Shares his/her thoughts."); } @Override public void breathe() { System.out.println("be alive; remain living. "); } @Override public void message() { System.out.println("life is a journey, keep moving and meet new people."); } public abstract void eat(); } |
Abstract method eat is implemented in a vegan class.
1 2 3 4 5 6 7 8 |
public class Vegan extends Person { @Override public void eat() { System.out.println("Eats vegan food"); } } |
While creating the object of person class and providing its reference to Vegan class we can call all the method written in Person class as well as eat method which is implemented in Vegan class.
1 2 3 4 5 6 7 8 9 10 |
public class Hello { public static void main(String[] args) { Person john = new Vegan(); john.breathe(); john.eat(); john.speak(); john.message(); } } |
Output:
1 2 3 4 5 6 7 |
be alive; remain living. Eats vegan food Shares his/her thoughts. life is a journey, keep moving and meet new people. |
Contributed by: Poonam Tomar
Few Docs have slight mistakes in O/p.