【问题标题】:Accessing Java default methods in a subinterface or implementation class访问子接口或实现类中的 Java 默认方法
【发布时间】:2014-12-03 07:19:07
【问题描述】:

我了解如果一个类重写了默认方法,您可以通过以下方式访问默认方法

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 应该可以在某个地方访问。

【问题讨论】:

  • 不,Java 中没有super.super。无论是 class 还是 interface 上的 default 方法,您永远无法访问在父级中被覆盖的方法。

标签: java methods interface overriding default


【解决方案1】:

您可以更上一层楼,因此 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
    }
}

【讨论】:

    猜你喜欢
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 2014-12-06
    • 2023-03-10
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多