What is a covariant return type in Java? In object-oriented programming in general?
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.
Java allows for Covariant Return Types, which means you can vary your return type as long you are returning a subclass of your specified return type. Method Overriding allows a subclass to override the behavior of an existing superclass method and specify a return type that is some subclass of the original return type.
The covariant return type A primitive type like int , float , reference , or void type can be the return value. As we said earlier, covariant return type means that a method's return type can be replaced with a narrower one when overridden in a subclass or child class.
In object-oriented programming, a covariant return type of a method is one that can be replaced by a "narrower" type when the method is overridden in a subclass. A notable language in which this is a fairly common paradigm is C++. C# supports return type covariance as of version 9.0.
Covariant return, means that when one overrides a method, the return type of the overriding method is allowed to be a subtype of the overridden method's return type.
To clarify this with an example, a common case is Object.clone()
- which is declared to return a type of Object
. You could override this in your own class as follows:
public class MyFoo { ... // Note covariant return here, method does not just return Object public MyFoo clone() { // Implementation } }
The benefit here is that any method which holds an explicit reference to a MyFoo object will be able to invoke clone()
and know (without casting) that the return value is an instance of MyFoo
. Without covariant return types, the overridden method in MyFoo would have to be declared to return Object
- and so calling code would have to explicitly downcast the result of the method call (even thought both sides "know" it can only ever be an instance of MyFoo).
Note that there's nothing special about clone()
and that any overridden method can have a covariant return - I used it as an example here as it's a standard method where this is often useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With