«Back to Home

Core Java

Topics

Covariant Return Type In Java

Covariant Return Type

In Java, covariant return types were introduced in JDK 1.5. Prior to Java5, we were not able to change the return type of the overridden method. Now, it is possible to override method by changing the return type, if subclass overrides any method that return type is non-primitive and it changes its return type of subclass type. It allows the programmer to program without the need of type checking and down casting.
 
Let’s see an example, given below.
 
Code
  1. class Bike {  
  2.     Bike run() {  
  3.         return this;  
  4.     }  
  5. }  
  6. public class Bullet extends Bike {  
  7.     Bullet run() {  
  8.         return this;  
  9.     }  
  10.     void displayMsg() {  
  11.         System.out.println("Hello, covariant return type");  
  12.     }  
  13.     public static void main(String args[]) {  
  14.         Bullet b = new Bullet();  
  15.         b.run();  
  16.         b.displayMsg();  
  17.     }  
  18. }  
21

Output

22
 
In the example, shown above, the return type of the run() method of Bike class is Bike and the return type of the run() method of bullet class is bullet. Both methods have different return types with the method overloading. This is called as a covariant return type.
 
Summary

Thus, we learnt that covariant return type allows the programmer to program without the need of type checking and down casting and also learnt how to use it.