What is a covariant return type? What is a covariant return type? java java

What is a covariant return type?


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.


Here is another simple example :

Animal class

public class Animal {    protected Food seekFood() {        return new Food();    }}

Dog class

public class Dog extends Animal {    @Override    protected Food seekFood() {        return new DogFood();    }}

It’s possible to modify the return type of the Dog’s seekFood() method to DogFood - a subclass of Food, as shown below:

@Overrideprotected DogFood seekFood() {    return new DogFood();}

That’s perfectly a legal overriding, and the return type of Dog’s seekFood() method is known as covariant return type.


From the release of JDK 1.5, covariant types were introduced in Java. and I'll explain it to you with a simple case, : When we override a function the function is allowed to make changes to it's behaviour that's what you get to read in most of the books, but what they { authors } miss out on is that we can change the return type too. check below link for clarification we can change the return type as long as it can be assigned to return type of Base version of the method.

So this feature of returning derived types is called COVARIANT...

Can overridden methods differ in return type?