by BehindJava

What is Covariant Return Type in java

Home » java » What is Covariant Return Type in java

In this tutorial we are going learn Covariant Return Type which an off the subject question for an interview.

With regards to method overriding the return type of the method must be same in the sub class and parent class which seems like limitation, and from Java 1.5 a new covariant return types feature was introduced by Sun Micro system.

With this feature it is possible to override any method by changing the return type only with rules mentioned below.

  1. If super class method return type is object then sub class method return type must be same or String, StringBuffer, Number or Integer, but not a primitive data type.
  2. If sub class method return type should not be parent type i.e. if super class method return type is string, then sub class method return type cannot be object.

Sample Code Snippet:

public class Covariant
{
	public Object refer()
	{
		System.out.println("Parent refernce");
		return null;
	}
}
public class ReturnType extends Covariant
{
	public String refer()
	{
		System.out.println("Return type class");
	    return null;
	}
}