Covariant Return Type


In Java programming language, by covariant return type we mean that the return type will or may vary in the same direction as that of the subclass. It means that when we are overriding methods, then the return type of that method can be a subtype of the overridden method’s return type.

When java5 was not introduced we could not override any method by changing the return type of the method. But after Java5 we can override the methods by changing the return type if any method is overridden by the subclass and whose return type is non primitive type but it changes its return type to subclass type.

Consider the following example in which it is demonstrated:


Simple example of covariant return type:

CODE:

class B {

B get () {

return this;

}

}

Class B1 extends B {

B1 get () {

return this;

}

void display () {

system. out. println (“Using covariant return type”);

}

public static void main (string args []) {

new B1. get (). display ();

}

}

OUTPUT:

Using covariant return type

In the above example the return type of the method get () of the class B is B and the return type of the get () method of the class B1 is B1. In the code above we can see that both of the methods have different return types but still this is method overriding. This concept of different return types but same name and same parameters is known as covariant return type.