Covariant return type in Java

The Java programming language allows covariant return type when overriding a superclass method in a sub-class method. Meaning, subclass method can vary the return type of an overridden method from the parent class, as long as the return type is a subtype of the parent class.

This feature is added in java 1.5. If a subclass is overriding a superclass method, the method name, return type, and parameters should exactly match. This was prior to Java version 1.5, But this is no longer necessary after the newly added feature.

Covariant return type example

Following is the example of covariant 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 the getObject() method, which returns the Vehicle object. We have a Car class, which overrides Vehicle class, but here return type is Car object, which is valid as a 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.

covariant return type

Conclusion

In this article, we learned about the covariant return types in Java.

Covariant return type in Java
Scroll to top

Discover more from ASB Notebook

Subscribe now to keep reading and get access to the full archive.

Continue reading