Explicitly Invoking Default Methods in Java
Java 8 introduced default methods in interfaces, enabling interface extension without modifying existing implementations. However, a question arises: can we explicitly invoke the default implementation of a method when it has been overridden or conflicts exist 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 explicitly call the default implementation of A.foo() from afoo() in class B, we can use the syntax:
A.super.foo();
This approach allows us to access the original default implementation of the method even when it has been overridden or there are conflicts with other default implementations.
In a more complex scenario, where multiple interfaces contain default methods with the same name, we can use the same syntax to choose the specific default implementation we want to use:
public class ChildClass implements A, C { @Override public void foo() { // Override and do something else // Or manage conflicts A.super.foo(); C.super.foo(); // Default implementation from C } public void bah() { A.super.foo(); // Default implementation from A C.super.foo(); // Default implementation from C } }
By explicitly invoking default methods, we can control how interfaces are extended, resolving conflicts and accessing original implementations as needed, without breaking the contract of overriding. This provides flexibility and customization in interface-based designs.
The above is the detailed content of How Can I Explicitly Call a Java Interface\'s Default Method After Overriding?. For more information, please follow other related articles on the PHP Chinese website!