【问题标题】:Why does order of implementing Interfaces (with default methods) matter in Java 8?为什么在 Java 8 中实现接口(使用默认方法)的顺序很重要?
【发布时间】:2015-12-16 06:51:11
【问题描述】:

众所周知,Java 可以实现多个interfaces。它们的实施顺序重要吗?我的意思是,在Java 8 中实现 B、C 是否与 C、B 相同?我的测试显示顺序是否很重要 - 但任何人都可以解释这背后的逻辑吗?

public interface A {
    public default void display() {
        System.out.println("Display from A");
    }
}

public interface B extends A {
    public default void display() {
        System.out.println("Display from B");
    }
}

public interface C extends A {
    public void display();
}

public interface D extends B, C {

}

上面的代码工作正常。如果我把B, C的顺序改成C, B,会报错:The default method display() inherited from B conflicts with another method inherited from C.

public interface D extends C, B {

}

编辑

我正在使用 Eclipse(火星)。 JDKjdk1.8.0_51。 JREjre1.8.0_60.

【问题讨论】:

  • 我错过了什么吗?如果我理解正确,您说使用一个订单时会出错,而使用其他订单时不会出错,这意味着订单有所不同,这意味着您回答了自己的问题。
  • 是的,我明白了。我只是想知道这背后是否有任何原因?
  • 无论顺序如何,您都应该得到相同的错误(意思是,在这两种情况下)。请再次检查!
  • 不;无论哪种方式都编译错误...

标签: java interface java-8 default-method


【解决方案1】:

无论哪种方式都应该有错误消息。当我使用 jdk 1.8.0_31 时,无论接口顺序如何,都会出现以下错误:

从 A.B 继承的默认方法 display() 与从 A.C 继承的另一个方法冲突

解决方案是在D 中覆盖display(),甚至只是告诉编译器要使用哪个超类的实现:

public interface D extends B, C {
    default void display(){
        B.super.display();
    }
}

或者重新制作display()摘要

interface D extends B, C {
    public void display();
}

如果您确实在使用比我更高的版本时遇到此错误,那么是否值得提交错误报告?

【讨论】:

  • D 也可以将display() 重新断言为摘要。
  • 错误(这是正确的行为)您在 1.8.0_40 中看到的相同。顺序没有区别。
【解决方案2】:

javac 的结果(所有版本 1.8.0_x):

error: interface D inherits abstract and default for display() from types B and C

ecj 4.4 的结果:

The default method display() inherited from B conflicts with another method inherited from C

结果来自 ecj >= 4.4.1:

NO ERROR

如果D的extends子句中的顺序发生变化,仍然ecj >= 4.4.1会正确报告错误。

我认为这是 Eclipse 中的一个错误,它是在 4.4.1 中引入的。我已提交bug 477891 跟进。

编辑: bug 477891 已在 Eclipse 4.6(GA:2016 年 6 月)的里程碑 3 中修复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-28
    • 2014-12-16
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    相关资源
    最近更新 更多