用相同的方法和不同的返回类型实现多个接口的Java
考虑下面的代码:
public interface A {
public A another();
}
public interface B {
public B another();
}
public interface AB extends A,B {
public AB another();
}
这会导致AB
上出现编译错误:
types B and A are incompatible; both define another(), but with unrelated return types
我已经看到了这个SO question,并遵循了公认答案中的不兼容示例,即
public interface C {
public void doSomething();
}
public interface D {
public boolean doSomething();
}
public interface CD extends C,D {
}
然而,在这种情况下,返回类型实际上是不兼容的——返回类型不能同时是void和boolean。然而,在我上面的示例中,AB
的another()
返回类型既是A
又是B
,因此可以实现这两个扩展接口
此外,在看过JLS(8.4.8、8.4.8.3、8.4.8.4)之后,我不太明白为什么我上面的例子是非法的。谁能给我解释一下吗
第二,除了重复A
或B
中的AB
合同要求之外,还有其他解决方案/变通办法吗
# 1 楼答案
对于Java 1.5之前的版本,会出现此错误消息(至少在Eclipse中将遵从性级别设置为1.4时,我可以重现此错误)。换句话说,确保你看到的是足够古老的规格
关于Java>;=1.5以下内容可供参考
正如您所说,因为
AB
既是A
又是B
,所以它满足两个接口这里引用了Java语言规范(第二版,即Java 1.4):
此外,当前的规格说明如下: