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

5
我了解如果一个类覆盖了默认方法,您可以以以下方式访问默认方法。
interface IFoo {
    default void bar() {}
}

class MyClass implements IFoo {
    void bar() {}
    void ifoobar() {
        IFoo.super.bar();
    }
}

但是如果一个接口覆盖了一个默认方法,那么父方法还能用吗?

在这种情况下,父方法仍然可以使用。

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
    }
}

Java中默认方法的措辞与类相似,否则会令人困惑/误导。子接口“继承”默认方法,并且可以“覆盖”它们。因此,IFoo.bar应该在某个地方可访问。


1
不,Java 中没有 super.super。无论是在父类中被覆盖的方法还是在接口中的 classdefault 方法,你都不能访问它。 - Boris the Spider
1个回答

2

您可以向上一级,因此在ISubFoo中可使用IFoo.super.bar()调用IFoo.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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接