Java covariant return type

Java Covariant Return Type

Java covariant return type refers toΒ return type of an overriding method in java. Method overriding is a run time polymorphism criteria. User uses it to provide the specific implementation of a method which is already provided by its super class. 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. This return type may vary in the same direction as the subclass.

Before JAVA 5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the covariant return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type.

Java Covariant Return Type Example

class X {    
X get() {
return this;
}    
}    
    
public class Y extends X {    
@Override  
Y get() {
return this;
}    
void message() {
System.out.println("welcome to Developer Helps");
}        
public static void main(String args[]){    
new Y().get().message();    
}    
} 

Output

welcome to Developer Helps