gpt4 book ai didi

Java - 使用相同的方法和不同的返回类型实现多个接口(interface)

转载 作者:搜寻专家 更新时间:2023-10-31 08:28:19 24 4
gpt4 key购买 nike

考虑以下代码:

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 值。而在我上面的示例中,ABanother() 返回类型既是 A 又是 B , 因此可以实现这两个扩展接口(interface)。

此外,在查看了 JLS(8.4.8、8.4.8.3、8.4.8.4)之后,我不太明白为什么我上面的示例是非法的。谁能给我解释一下?

其次,除了在 AB 中重复 AB 的契约(Contract)要求外,是否有任何解决方案/解决方法?

最佳答案

此错误消息出现在 Java 1.5 之前的版本中(至少我可以在 Eclipse 中将合规级别设置为 1.4 时重现该错误)。换句话说,确保您查看的是足够旧的规范。

在 Java >= 1.5 上,以下编译正常。

interface A {
public A another();
}

interface B {
public B another();
}

interface AB extends A,B {
public AB another();
}

正如您所说,由于 AB 既是 A 又是 B,因此它满足这两个接口(interface)。


这里引用了 Java 语言规范(第二版,即 Java 1.4):

9.2 Interface Members

The members of an interface are:

  • Those members declared in the interface.
  • Those members inherited from direct superinterfaces.
  • If an interface has no direct superinterfaces, [...]

It follows that it is a compile-time error if the interface declares a method with the same signature and different return type or incompatible throws clause.

此外,当前规范说明如下:

9.4.2 Overloading

If two methods of an interface (whether both declared in the same interface, or both inherited by an interface, or one declared and one inherited) have the same name but different signatures that are not override-equivalent (§8.4.2), then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures that are not override-equivalent.

关于Java - 使用相同的方法和不同的返回类型实现多个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11343238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com