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

后端 未结 2 1692
野性不改
野性不改 2021-01-02 05:18

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

2条回答
  •  孤城傲影
    2021-01-02 05:43

    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.

提交回复
热议问题