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

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

Simple example of Covariant Return Type


class A{    
A get(){return this;}    
class B1 extends A{    
B1 get(){return this;}    
void message(){System.out.println("welcome to covariant return type");}    
public static void main(String args[]){    
new B1().get().message();    

As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.

Advantages of Covariant Return Type

Following are the advantages of the covariant return type.

  1. Covariant return type assists to stay away from the confusing type casts in the class hierarchy and makes the code more usable, readable, and maintainable.
  2. In the method overriding, the covariant return type provides the liberty to have more to the point return types.
  3. Covariant return type helps in preventing the run-time ClassCastExceptions on returns.