Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly calling a default method in Java

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?

like image 398
GOTO 0 Avatar asked Nov 14 '13 11:11

GOTO 0


People also ask

Can we call default method in Java 8?

Interfaces can have default methods with implementation in Java 8 on later. Interfaces can have static methods as well, similar to static methods in classes. Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.

Can you override default method Java?

A default method cannot override a method from java.

How do you use the default method in functional interface?

You can have default methods in a functional interface but its contract requires you to provide one single abstract method (or SAM). Since a default method have an implementation, it's not abstract. Conceptually, a functional interface has exactly one abstract method.


1 Answers

As per this article you access default method in interface A using

A.super.foo(); 

This could be used as follows (assuming interfaces A and C both have default methods foo())

public class ChildClass implements A, C {     @Override         public void foo() {        //you could completely override the default implementations        doSomethingElse();        //or manage conflicts between the same method foo() in both A and C        A.super.foo();     }     public void bah() {        A.super.foo(); //original foo() from A accessed        C.super.foo(); //original foo() from C accessed     } } 

A and C can both have .foo() methods and the specific default implementation can be chosen or you can use one (or both) as part of your new foo() 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.

like image 96
Richard Tingle Avatar answered Nov 15 '22 18:11

Richard Tingle