Search code examples
javainterfacesuperdefault-method

Is calling a superinterface's default method possible?


Say I have two classes, A and B:

class A
{
    void method()
    {
        System.out.println("a.method");
    }
}
class B extends A
{
    @Override
    void method()
    {
        System.out.println("b.method");
    }
}

After instantiating B as b, I can call B's method like b.method(). I can also make B's method call A's method with super.method(). But what if A is an interface:

interface A
{
    default void method()
    {
        System.out.println("a.method");
    }
}
class B implements A
{
    @Override
    void method()
    {
        System.out.println("b.method");
    }
}

Is there any way I can make B's method call A's method?


Solution

  • Yes, you can. Use

    A.super.method();
    

    The JLS states

    If the form is TypeName . super . [TypeArguments] Identifier, then:

    It is a compile-time error if TypeName denotes neither a class nor an interface.

    If TypeName denote a class, C, then the class to search is the superclass of C.

    It is a compile-time error if C is not a lexically enclosing type declaration of the current class, or if C is the class Object.

    Let T be the type declaration immediately enclosing the method invocation. It is a compile-time error if T is the class Object.

    Otherwise, TypeName denotes the interface to be searched, I.