Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 785
aioobe Avatar asked Sep 20 '10 11:09

aioobe


People also ask

Does Java allow covariant return types?

The covariant return types are newly introduced since Java 5.0, and used during method overriding. Covariant return type allows us to change the return type of the overriding method in the subclass; however this return type in subclass method must be a subtype of super class method return type.

Why do we use covariant return type in Java?

Covariant return type refers to return type of an overriding method. It allows to narrow down return type of an overridden method without any need to cast the type or check the return type. Covariant return type works only for non-primitive return types.

Does return type matter in method overriding in Java?

The overriding method was said to be invariant with respect to return type. Java version 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child's return type should be a subtype of the parent's return type.

Can we have different types of return if we override the class?

Yes. It is possible for overridden methods to have different return type .


2 Answers

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.

like image 200
Péter Török Avatar answered Oct 31 '22 19:10

Péter Török


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

like image 25
irreputable Avatar answered Oct 31 '22 20:10

irreputable