Covariant return types in Java

In this tutorial, we will learn about covariant return types in Java.

This concept is based on Method Overriding in Java.

To understand the concept of method overriding, read:

Runtime Polymorphism or Dynamic Method Dispatch in Java

Before Java 5.0, there were certain rules of overriding. When we override a method name, parameters and return type should be the same for overriding and overridden methods.

After Java 5.0, the overriding method of the child class can have different return types. The return type of child class should be sub-type of the return type of parent class. Since now return type can be varied, this is known as covariant type in Java.

Example of Covariant return types in Java

The example of the covariant return type is shown below. Here, the overridden method of a sub-class has a different return type as that of the overriding method of a parent class.

public class A{ 
A learn(){ 
System.out.println("In A"); 
return new A() ;    // return type of method A is class itself 
   
  } 
}
 public class B extends A{ 
@override 
B learn(){ 
System.out.println(" In B");

 return new B(); // return type of sub-class is different from base class 
  
}

public static void main(String[] args){ 
    A c = new B();
    c.learn();
 }
}

The output will be:

In B

Please note, Overriding method can either return sub-class type or super-class type.

As mentioned, the child return type should be of sub-type of parent’s return type. So, what is the sub-type? Read the following code to understand.

public class parent{
    
      public Number m(){
         return null ;
     }
}

public class child extends parent{

      public Integer m(){
         return null ;
     }
}

In this example, Number is a return type of parent class. The Number itself is a class in Java. In a sub-class, we return the IntegerĀ type.

The IntegerĀ is also a class in java and it extends Number class. Therefore, Integer is a sub-type of Number.

Also read: Password Validation Program in Java

Leave a Reply

Your email address will not be published. Required fields are marked *