Covariant return type in Java

In context of method overriding, the return type of the overriding method can be a subtype of the return type of the overridden method. This is called covariance of the return types.

It is based on the Liskov Substitution Principle and it was introduced in the Java programming language in  JDK version 1.5

Output :

In the example above, the overridden method returns an object of type Fruit while the overriding method returns object of type Mango. Note that Mango is a subclass of Fruit class.


1. Evolution

  • Before JDK1.5, when you override a superclass method, the name, argument types and return type of the overrding method has to be exactly same as that of superclass method. So the overriding method is said to be invariant with respect to argument types and return type.
  • This is relaxed in JDK1.5 and successive versions. The return type of the overriding method can be a subtype of the return type of the overridden method. This is called covariance of the return types.

 


2. Implementation

  • Although the return type based overloading is not allowed by java language, JVM always allowed return type based overloading. JVM uses full signature of a method for lookup / resolution. Full method signature includes return type in addition to argument types. i.e. a class can have two or more methods differing only by return type. javac uses this fact to implement covariant return types.
  • Note that we still can’t use return type based overloading in source language. But, this is used by javac to support covariant return types. This way, there is no change needed in the JVM to support covariant return types.

Source : oracle