Home >Java >javaTutorial >How Can You Explicitly Invoke a Default Method\'s Implementation in Java When It\'s Overridden?
Overriding Default Methods in Java
Default methods introduced in Java 8 provide extensibility to interfaces without the need for modifying existing implementations. However, the question arises whether it's possible to explicitly invoke the default implementation when it has been overridden or there are conflicts due to multiple default implementations in different interfaces.
Consider the following example:
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? } }
To invoke the default implementation of foo in class B, you can use A.super.foo().
public void afoo() { A.super.foo(); }
This syntax allows you to access the original default implementation even when the method has been overridden in the implementing class.
In cases where multiple interfaces have default methods with the same signature, such as interfaces A and C both having a foo method, you can select the specific default implementation you want to invoke:
public class ChildClass implements A, C { @Override public void foo() { A.super.foo(); // Accesses original foo() from A C.super.foo(); // Accesses original foo() from C } }
This syntax provides flexibility in choosing the default implementation you desire, or you can even incorporate both implementations into your own custom foo method. The method invocation syntax is formally described in chapter 15 of the Java Language Specification.
The above is the detailed content of How Can You Explicitly Invoke a Default Method\'s Implementation in Java When It\'s Overridden?. For more information, please follow other related articles on the PHP Chinese website!