如果我有这个界面:
public interface Foo {
void bar();
}
为什么我不能这样实现?
public class FooImpl implements Foo {
@Override
public Object bar() {
return new Object();
}
}
似乎 void 应该与所有事物都是协变的。我错过了什么吗?
编辑: 我应该更清楚我正在寻找设计理由,而不是它无法编译的技术原因。让 void 对所有事物都协变会产生负面影响吗?
最佳答案
void
仅与 void
协变,因为 the JLS says so :
A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:
If R1 is
void
then R2 isvoid
.If R1 is a primitive type, then R2 is identical to R1.
If R1 is a reference type then:
R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or
R1 = |R2|
关于java - 为什么 void 在 Java 中不是协变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14219529/