Covariant Return Types

      No Comments on Covariant Return Types




Covariant Return Types concept was introduced in Java5. Covariant Return Types are not possible before Java5.

Covariant Return Type means that the return type of overridden method can vary in the direction of subclass. i.e. Return type of Overridden method in the subclass can be subclass of the return type of method in superclass.

Program to Explain Covariant Return Types:

package com.masterjavatutorial;
public class Test {

	public Number getNumber(){
  	   return 100;
	}
	
	public static void main(String[] args) {
	   Test t = new Example();
	   System.out.println(t.getNumber());
	}

}


package com.masterjavatutorial;
public class Example extends Test{

	@Override
	public Integer getNumber(){
	   System.out.println("In Subclass"); 
	   return 400;
	}
	
}

Here, in the above example, method getNumber() is overridden but the return types are different. In the Superclass, it is Number whereas in the Subclass it is Integer.

Here, Number and Integer are Covariant Return types as Number is the Superclass of Integer.

Output of the above Program is as below:

In Subclass
400