Explicitly calling a default method in Java

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.

Leave a Comment