What is Covariant return types in Java

Covariant Return Type :

It's a common question for the interview. Several times interviewer asks this question after the overloading or overriding concept. Because this is related to overriding.

 

The covariant return type specifies that the return type may vary in the same direction as the subclass.

Earlier Java5, it was not possible to override any method by changing the return type. We can not change override a method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.

 

That means if Let's take a simple example:

class Base{
A get(){return this;}
}

class Derrived extends Base{
Derrived  get(){return this;}
void message(){System.out.println("welcome to covariant return type");}

public static void main(String args[]){
new Derrived  ().get().message();
}
}

Related Articles

post a comment