Learnitweb

default methods in interface in case of multiple inheritance

When a class implements two interfaces, each having default methods with same signature, it results in compile time error. To understand this with an example, we have created two interfaces: Left and Right. Class Test implements these two interface.

interface Left {
	public default void play() {
		System.out.println("play method of Left interface");
	}
}

interface Right {
	public default void play() {
		System.out.println("play method of Right interface");
	}
}

public class Test implements Left, Right {

}

On compilation, above code will result in following error:

Test.java:12: error: class Test inherits unrelated defaults for play() from types Left and Right
public class Test implements Left, Right{
       ^
1 error

The reason for above error is that we have not specified with default method functionality should be used in Test class. It will not be possible for the Test class to use both method’s functionality (i.e. two methods with same signature).

What is the solution

The solution is very simple. Test class should specify it’s own implementation for the default method.

Class implementing interfaces need to override the default method.

Method 1: Test class can specify it’s own implementation

Test class can override the play method with it’s own functionality.

public class Test implements Left, Right {
	@Override
	public void play() {
		System.out.println("play method of Left interface");
		System.out.println("play method of Right interface");
	}
}

Method 2: Test class can override default method of implemented interface

Method in class can override any of the default method of implemented interfaces. Following are the two valid implementations:

public class Test implements Left, Right {
	@Override
	public void play() {
		Left.super.play();
	}
}
public class Test implements Left, Right {
	@Override
	public void play() {
		Right.super.play();
	}
}

Note the two ways of calling play method of Left and Right interfaces: Left.super.play() and Right.super.play(). This is how we use the default method of the implemented interface.