Friday, March 25, 2022

Covariant Return Type in Java

Before Java 5, when you overrode 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 overridden method's return type may be different from super-class method's return type but the return type of the subclass' method 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 a subtype of R1. That is known as covariant return type in Java.

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

Covariant return type in Java example

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

//sub-class of A, also used as return type
class B extends A{
 B(String name){
  super(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);
 }
}

Output

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 a 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!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Varargs (Variable-length Arguments) in Java
  2. Enum Type in Java
  3. Method Overriding in Java
  4. Inheritance in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. strictfp in Java
  2. static Import in Java With Examples
  3. Type Erasure in Java Generics
  4. Constructor Chaining in Java
  5. Interface Default Methods in Java
  6. Fail-Fast Vs Fail-Safe Iterator in Java
  7. Difference Between Comparable and Comparator in Java
  8. Deadlock in Java Multi-Threading