4

我有以下代码片段

public class Test {
    static interface I1 { I1 m(); }

    static interface I2 { I2 m(); }

    static interface I12 extends I1,I2 { I12 m(); }

    public static void main(String [] args) throws Exception {
    }
}

当我尝试编译它时,我得到了错误。

Test.java:12: types Test.I2 and Test.I1 are incompatible; both define m(), but with unrelated return types.

如何避免这种情况?

4

4 回答 4

2

正如Java - 接口实现中的方法名称冲突中所讨论的,您不能这样做。

作为一种解决方法,您可以创建一个适配器类。

于 2012-03-14T15:02:03.113 回答
1

只有一种情况会起作用,xamde提到了这种情况,但没有彻底解释。它与协变返回类型有关。

在 JDK 5 中,协变返回添加的位置,因此以下是一个有效的情况,可以正常编译并运行而不会出现问题。

public interface A {
    public CharSequence asText();
}

public interface B {
    public String asText();
}

public class C implements A, B {

    @Override
    public String asText() {
        return "C";
    }

}

因此,以下将运行而不会出现错误并将“C”打印到主输出:

A a = new C();
System.out.println(a.asText());

这是因为 String 是 CharSequence 的子类型。

于 2012-05-16T18:07:34.277 回答
1

这是Sun 的 Java 6 编译器中的一个错误

于 2013-06-24T14:23:21.900 回答
0

我遇到了同样的问题,使用 Oracle 的 JDK 7 似乎没问题。

于 2012-05-16T17:40:48.543 回答