Java allows co-variant return type when overriding a super class method in a sub class method. Meaning, subclass method can vary return type of a overridden method from parent class, as long as the return type is sub type of the parent class. This feature is introduced in java 1.5. Prior to java 1.5, if a subclass is overriding a super class method, it’s method name, return type and parameters should exactly match. But this is no longer required with covariant return type feature.

Following is the example of covariant return type implementation in java.

package com.asb;

public class Test {
	
	public static void main(String args[]) {
		Vehicle vehicle = new Car();
		vehicle.getObject();
	}
}
class Vehicle {
	//class method, which returns Vehicle object
	public Vehicle getObject(){
		System.out.println("returning vehicle object");
		return new Vehicle();
	}
}

//Car class inherits Vehicle class notice that return type is Car	
class Car extends Vehicle {
	//Override run() method of Vehicle class but return 	
	public Car getObject(){
		System.out.println("returning car object");
		return new Car();
	}		
}

In the above example, we have a Vehicle class, with getObject() method, which returns Vehicle object. We have a Car class, which overrides Vehicle class, but here return type is Car object, which is valid as return type(Car object) is covariant(of class Vehicle) return type.

Running the above program will print the text “returning car object” as shown below, as expected as we are overriding the Vehicle class’s getObject() method.

You may also be interested in :