java - 为什么 void 在 Java 中不是协变的?

标签 java polymorphism covariance

如果我有这个界面:

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

  • 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/

相关文章:

java - Java中的多态和接口(interface)(多态可以用来实现接口(interface)吗……为什么?)

c++ - 如何为相同类型的组合成员正确设置值

c# - C# 4.0 中协变和逆变的良好现实用例示例?

java - Java 可以转换任何东西吗?

java - 使用和/或提取可扩展文件 (obb) android

java - 通过 jakson Java 使用嵌套多态对象进行反序列化

scala - 类型成员和协方差

Python:如何计算协方差矩阵并像 map 结构一样导出数据

java.lang.NoClassDefFoundError : gherkin/IGherkinDialectProvider while running Selenium-Cucumber test 错误

java - 在我的网站中添加 Facebook 登录信息