What is a covariant return type?
What is a covariant return type in Java? In object-oriented programming in general?
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:
@Override
protected 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?
covariant Return types simply means returning own Class reference or its child class reference.
class Parent {
//it contain data member and data method
}
class Child extends Parent {
//it contain data member and data method
//covariant return
public Parent methodName() {
return new Parent();
or
return Child();
}
}
To add to the above answers, overriding is possible among co-variant return types, with the constraint that the return type of the overriding method (subclass method) should be a subclass of the return type of the overridden method (superclass method). This is valid from Java 5 onwards.