In java8 , a new concept is introduced wherein we can provide implementation for methods in an interface using default keyword. But what will happen if a class implements two interfaces with same default methods , which method the implementing class will inherit. Let us see this in the following working example.
I have one interface, TestInterface1 with a default method test()
package com.test;
public interface TestInterface1 {
public default void test() {
System.out.println(“hi”);
}
}
An another interface, TestInterface2 too has implementation for method test()
package com.test;
public interface TestInterface2 {
default public void test() {
System.out.println(“hello”);
}
}
Now, if I have a class Test that implements above two interfaces , the compiler gives me an error “Duplicate default methods named test with the parameters () and () are inherited from the types TestInterface2 and TestInterface1”
package com.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.*;
import java.lang.reflect.Method;
public class Test implements TestInterface1,TestInterface2{
public static void main(String[] args) {
Test test=new Test();
test.test();
}
However, I can remove the above error by providing the compiler which interface method implementation I need in my implementation class.
package com.test;
public class Test implements TestInterface1,TestInterface2{
public static void main(String[] args) {
Test test=new Test();
test.test();
}
@Override
public void test() {
// TODO Auto-generated method stub
TestInterface1.super.test(); }
}
So, as shown above in my implementation class method I need to call the method with the interface name whose method implementation I need.