Covariant Return Type in Java
Overview
Before Java 5 It was restricted to return a subtype from an overridden method of the child class. for example- In the below code getVehicle() method from Vehicle class is returning Car but in its child class SportsVehicle we are returning SportsCar which is a subtype of Car. Covariant Return type allows the more specific return type from the child class.
Example
class Car{
public String toString(){
return "Toyota";
}
}
class SportsCar extends Car{
public String toString() {
return "Porsche";
}
}
class Vehicle{
Car getVehicle() {
return new Car();
}
}
class SportsVehicle extends Vehicle{
@Override
SportsCar getVehicle() {
return new SportsCar();
}
}
public class CovariantReturnType {
public static void main(String[] args) {
Vehicle v = new Vehicle();
Car car = v.getVehicle();
System.out.println(car);
v = new SportsVehicle();
car = v.getVehicle();
System.out.println(car);
}
}
Output:
Toyota
Porsche