Wednesday, 13 May 2015

covariant return type in Java

Before Java 5, when you override a superclass method in a subclass the method signature had to be exactly same, i.e., the name, argument types and return type of the overriding method in the sub-class had to be exactly same as that of the super-class method.

This is relaxed a bit in Java 5 in case of return type. The sub-class method's return type may be different from super-class method's return type but the return type of the subclass should be a subtype of return type of super class method.
Which means, if method in the super-class has return type R1 and the overriding method in the subclass has return type R2 then R2 must be the subtype of R1. That is known as covariant return type.

Covariant name comes from the fact that the type of the return is allowed to vary in the same direction as the subclass.

Example of Covariant return type

// used as return type
class A{
 String name;
 A(String name){ = name;

//sub-class of A, also used as return type
class B extends A{
 B(String name){

class C{
 public A getValue(){
  return new A("Test A");

class D extends C{
 // overriding method, returning subtype of the 
 // super class method
 public B getValue(){
  return new B("Test B");

public class CovariantDemo {

 public static void main(String[] args) {
  // Reference of Class C
  C c;
  // pointing to class C
  c = new C();
  System.out.println("Value from class C " + c.getValue().name);
  // now pointing to class D
  c = new D();
  System.out.println("Value from class D " + c.getValue().name);




Value from class C Test A
Value from class D Test B

It can be seen from the program that in class D which is the sub class of class C, getValue() method is overridden. In class C's getValue() method return type is A where as in the overridden method in class D return type is B, which is sub type of A. Making it covariant return type.

That's all for this topic covariant return type in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. Method overloading in Java
  2. Method overriding in Java
  3. varargs in Java
  4. Inheritance in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java advance topics page

No comments:

Post a Comment