在子接口或实现类中访问Java默认方法

rjh*_*sgc 5 java methods overriding default interface

我了解如果类覆盖默认方法,则可以通过以下方式访问默认方法

interface IFoo {
    default void bar() {}
}

class MyClass implements IFoo {
    void bar() {}
    void ifoobar() {
        IFoo.super.bar();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果接口覆盖默认方法,情况又如何呢?父方法有任何可用方式吗?

interface IFoo {
    default void bar() {}
}

interface ISubFoo extends IFoo {
    // is IFoo.bar available anywhere in here?
    default void bar {}
} 

class MyClass implements ISubFoo {
    // is IFoo.bar available anywhere in here too?

    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.bar(); // calls ISubFoo.bar
    }
}
Run Code Online (Sandbox Code Playgroud)

Java用于默认方法的语言类似于类,否则会造成混淆/误导。子接口“继承”默认方法,并且可以“覆盖”它们。因此,似乎IFoo.bar应该可以在某处访问。

Erw*_*ier 2

您可以向上一级,因此IFoo.bar()可以在 ISubFoo 中使用IFoo.super.bar().

interface IFoo {
    default void bar() {}
}

interface ISubFoo extends IFoo {
    // is IFoo.bar available anywhere in here?
    // Yes it is
    default void bar {
        IFoo.super.bar()
    }
} 

class MyClass implements ISubFoo {
    // is IFoo.bar available anywhere in here too?
    // Not it is not

    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.bar(); // calls ISubFoo.bar
    }
}
Run Code Online (Sandbox Code Playgroud)