Tuesday, 15 September 2009

Covariant Return Types in Java 5

Covariant return types are one of the newly added features in Java 5. Using covariant return types, an overridden method in a derived class can return a type derived from the type returned by the base-class method.

For example in the Java versions prior to Java 5, the following would have thrown a compile time error.

class Vehicle
Vehicle myFunc(){return this;}

class Car extends Vehicle
// myFunc() returns Car, which is a subclass of Vehicle
Car myFunc(){return this;}
public void printMe(){ System.out.println("I am a Car");}

public class Covariant {

public static void main(String args[]) 
Car car = new Car();

CompileTime Error: The return type is incompatible with Vehicle.myFunc()

Prior to Java 1.5, to remove this error you had to make 2 changes.

1. Change the return type of derived class myFunc() to Vehicle and
2. Downcast Object being returned by car.myFunc() to Car

Java 5 lets you get away with that and makes the above code work just fine.