2012-03-14 26 views
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. 

如何避免这种情况?

+1

[在一个类中使用相同的方法实现2个接口的可能的重复。哪种接口方法被重写?](http://stackoverflow.com/questions/2801878/implemeting-2-interfaces-in-a-class-with -same-method-which-interface-method-is-o) – Matthias 2012-03-14 14:49:11

+0

或更好的重复:http://stackoverflow.com/questions/2598009/method-name-collision-in-interface-implementation-java – Matthias 2012-03-14 14:51:00

+0

我读过这些问题,但我没有看到我的问题的答案,我可以如何避免这种情况? – 2012-03-14 14:52:48

回答

0

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

1

只有一种情况会发生这种情况,xamde提到这种情况,但没有详细解释。这与covariant return types有关。

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

这工作,因为字符串是CharSequence的一个亚型。