Java 8 introduces default methods to provide the ability to extend interfaces without the need to modify existing implementations.
I wonder if it's possible to explicitly invoke the default implementation of a method when that method has been overridden or is not available because of conflicting default implementations in different interfaces.
interface A {
default void foo() {
System.out.println("A.foo");
}
}
class B implements A {
@Override
public void foo() {
System.out.println("B.foo");
}
public void afoo() {
// how to invoke A.foo() here?
}
}
Considering the code above, how would you call A.foo()
from a method of class B?
Best Answer
As per this article you access default method in interface
A
usingThis could be used as follows (assuming interfaces
A
andC
both have default methodsfoo()
)A
andC
can both have.foo()
methods and the specific default implementation can be chosen or you can use one (or both) as part of your newfoo()
method. You can also use the same syntax to access the default versions in other methods in your implementing class.Formal description of the method invocation syntax can be found in the chapter 15 of the JLS.