This article explains how default methods enable multiple inheritance of behavior in Java 8 using the new default methods feature in Interfaces.
Multiple Inheritance of Behavior with Default Methods
Until Java 7 multiple interface inheritance was possible but interfaces were not allowed to have concrete methods. Thus, behavior inheritance was not possible. With Java 8, where interfaces can now have default methods
Click to Read Default Methods tutorial implemented in them, it is now possible to have a derived class inherit methods from multiple parent interfaces. So, multiple inheritance of behavior is now possible.
Example to understand multiple inheritance using default methods
In the above class diagram –
- A is an interface with a default implemented method
- B is an interface with a default implemented method
- C is a concrete class implementing both A and B interfaces.
Now, since C implements both A & B interfaces, it inherits the default methods of both the interfaces. An instance of C can thus be used to invoke default methods of A and B. Lets see code of such an invocation on class C below, starting off with code defining interfaces A & B –
- In the
main()method of C an instance of C called cObj is created.
printUsingB()are invoked on cObj.
- Multiple inheritance of behavior is thus achieved as C inherits 2 implemented methods(or behaviors from A & B).
Conflict Resolution in case of inheriting methods with same signature
We just saw above how C inherits implemented default methods from interfaces A & B. The two inherited methods had different names so there was no confusion. But what if the default methods being inherited had the same signatures – same name and same return types. Java 8 provides resolution rules for this.
I have covered conflict resolution rules for such scenarios and the classic diamond problem resolution in my next article which you can read hereRead tutorial on Java 8 multiple inheritance conflict resolution and diamond problem.