Java 8 Multiple Inheritance of Behavior from Interfaces using Default Methods

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

Multiple Inheritance Using Default Methods

In the above class diagram –

  • A is an interface with a default implemented method printUsingA().
  • B is an interface with a default implemented method printUsingB().
  • 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 –

Java 8 code showing multiple inheritance for interfaces A,B & class C
//A.java
public interface A{
  public default void printUsingA(){
    System.out.println("Print from A");
  } 
}
//B.java
public interface B{
  public default void printUsingB(){
    System.out.println("Print from B");
  } 
} 
//C.java
public class C implements A,B{
  public static void main(String args[]){
    C cObj=new C();
    cObj.printUsingA();
    cObj.printUsingB();
  }  
}
 OUTPUT of the above code
Print from A
Print from B
Explanation of the code

  • In the main() method of C an instance of C called cObj is created.
  • Methods printUsingA() & 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.

 

Digiprove sealCopyright © 2014-2016 JavaBrahman.com, all rights reserved.