Why doesn't Java 5+ API take advantage of covariant return types?

為{幸葍}努か 提交于 2019-11-30 14:58:38

问题


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

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.


回答1:


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.

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

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




回答2:


That would break binary compatibility. Previously compiled classes cannot find the method with the new return type. JLS3 §13.4.15, §13.4.12



来源:https://stackoverflow.com/questions/3751160/why-doesnt-java-5-api-take-advantage-of-covariant-return-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!