为什么Java中的void不协变? [英] Why is void not covariant in Java?

查看:135
本文介绍了为什么Java中的void不协变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这个界面:

public interface Foo {
    void bar();
}

为什么我不能像这样实现它?

Why can't I implement it like this?

public class FooImpl implements Foo {
    @Override
    public Object bar() {
         return new Object();
    }
}

似乎无效应与所有事物协调。我错过了什么吗?

It seems like void should be covariant with everything. Am I missing something?

编辑:
我应该更清楚我正在寻找设计理由,而不是技术原因它不会编译。对所有事物进行空洞协变是否会产生负面影响?

I should have been clearer that I'm looking for the design justification, not the technical reason that it won't compile. Are there negative consequences to making void covariant to everything?

推荐答案

技术上 void 不能是协变返回类型,因为调用者需要知道堆栈布局。
在INVOKEVIRTUAL / INTERFACE之后,调用返回对象的函数将导致堆栈顶部的对象引用。 Void 返回类型不会在堆栈顶部留下任何内容,因此函数是二进制不兼容的。

Technically void cannot be a covariant return type as the caller needs to know the stack layout. Calling a function that returns an object would result of an object-ref on the top of the stack after the INVOKEVIRTUAL/INTERFACE. Void return type leaves nothing on the top of the stack, hence the functions are binary incompatible.

所以JLS理所当然地说这是不可能的。

So the JLS rightfully says it's not possible.

这篇关于为什么Java中的void不协变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆