为什么Java 5+ API不利用协变返回类型? [英] Why doesn't Java 5+ API take advantage of covariant return types?

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

问题描述

从Java 5开始,我们可以协变返回类型。为什么Java API没有利用这个?

Since Java 5 we are allowed to have covariant return types. Why doesn't the Java API take advantage of this?

Graphics2D.create()为例。为什么不重写返回 Graphics2D 对象?在我看来,它在所有情况下都是向后兼容的。

Take Graphics2D.create() for instance. Why isn't it overridden to return a Graphics2D object? It seems to me that it would be backward compatible in all situations.

推荐答案

一般来说,这确实是为了保持向后兼容性。请注意,兼容性也必须保持在字节码级别,并且更改返回类型会更改字节码。所以一般来说,如果有任何子类可能覆盖了有问题的方法,切换到协变返回类型会破坏这些类。

In general, this is indeed in order to maintain backward compatibility. Note that the compatibility must be kept on the bytecode level too, and changing the return type changes the bytecode. So in general, if there are any subclasses which may have overridden the method in question, switching to a covariant return type would break those classes.

Graphics2D 是抽象的,它显然是要子类化的,因此上述推理适用。

Since Graphics2D is abstract, it is obviously meant to be subclassed, so the above reasoning applies.

Java Generics and Collections 虽然更多地侧重于泛型的观点,但在8.4节中讨论了协变覆盖。

Java Generics and Collections, although focuses more on the generics point of view, contains a discussion on covariant overriding in section 8.4.

这篇关于为什么Java 5+ API不利用协变返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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