我有以下代码片段

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

如何避免这个?

有帮助吗?

解决方案

java - 方法名称碰撞在界面实现中碰撞你不能这样做。

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

其他提示

只有一种情况,其中它可以工作,这是由 xamde 的提到的,但未彻底解释。它与协会返回类型

在JDK 5中,Covariant返回,其中添加,因此以下是一个有效的案例,它将编译良好并运行而不存在问题。

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());
.

这是作品,因为字符串是charsequence的子类型。

这是一个 sun的java 6编译器

我有同样的问题,通过使用Oracle的JDK 7似乎很好。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top