Is calling a superinterface's default method possible? [duplicate]

一曲冷凌霜 提交于 2019-12-25 02:47:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/22913784/is-calling-a-superinterfaces-default-method-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!