January 5, 2024

Covariant Return Type in Java

In this tutorial, we'll discuss covariant return type in Java which was added in Java 5. Method overriding in Java is said to be covariant with respect to return type which means that the return type is allowed to vary in the same direction as the subclass.

What is covariant return type in Java

First let’s try to understand what exactly does this covariant return type mean? Before Java 5 it was not possible to change the return type of the overridden method in the sub-class meaning the method in the parent class and the overridden method in the child class should have the same name, same number and type of arguments and same return type.

Java 5 onward, because of this covariant return type feature, it is possible for the overridden method to have different return type from the method in the parent class. There is one restriction though, the return type of the sub-class method must be a subtype of the return type of the parent class method.

For example- In parent class there is a method with return type R1. In the sub-class overridden method may have a different return type R2 but R2 must be a subtype of R1.

Java covariant return type example

In the example Child class extends Parent and also overrides the method getInstance(). As you can see that getInstance() method of the Parent class returns an object of type Parent where as getInstance() method of the Child class returns an object of type Child. That can be done because Child is a subtype of Parent in this example.

class Parent{
  Parent getInstance(){
    return new Parent();
  }
  void parentTest(){
    System.out.println("In parent class method");
  }
}
class Child extends Parent{
  // return type is subtype here
  Child getInstance(){
    return new Child();
  }
  void childTest(){
    System.out.println("In child class method");
  }
}
public class CovariantDemo {

  public static void main(String[] args) {
    Parent pobj = new Parent();
    Child cobj = new Child();
    pobj.getInstance().parentTest();
    cobj.getInstance().childTest();
  }
}
Output
In parent class method
In child class method

That's all for the topic Covariant Return Type in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment