Calling Default Methods in Java
Question:
Is it possible to invoke the default implementation of a method when it has been overridden or conflicts with implementations in multiple interfaces? Consider the following code:
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? } }
Answer:
The default method A.foo() can be explicitly invoked using the syntax A.super.foo(). This syntax allows you to access the original implementation of the method even if it has been overridden or is not available due to conflicts.
Example:
To call A.foo() from the method afoo() in class B, you can use the following code:
public void afoo() { A.super.foo(); }
Additional Use:
The super syntax can also be used to access default methods from other interfaces. For example, if interface C also has a default method foo(), you can access both implementations in class B as follows:
public void bah() { A.super.foo(); // Original `foo()` from interface `A` C.super.foo(); // Original `foo()` from interface `C` }
By using the super syntax, you can selectively choose which default implementation to invoke or combine multiple implementations in your own methods.
The above is the detailed content of How to Call Default Methods in Java When Overridden or Conflicting?. For more information, please follow other related articles on the PHP Chinese website!