covariant return type in java with example

Covariant return type is a feature introduced in Java 5 that allows a subclass method to return a type that is a subclass of the type returned by the superclass method. This means that the return type of the subclass method can be more specific than the return type of the superclass method.

Here is an example of covariant return type:

public class Animal {
    public Animal reproduce() {
        return new Animal();
    }
}

public class Dog extends Animal {
    @Override
    public Dog reproduce() {
        return new Dog();
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        Animal newAnimal = animal.reproduce(); // returns an Animal object

        Dog dog = new Dog();
        Dog newDog = dog.reproduce(); // returns a Dog object
        Animal anotherNewDog = dog.reproduce(); // also returns a Dog object, but can be cast to Animal
    }
}

In this example, the superclass Animal has a method reproduce() that returns an Animal object. The subclass Dog overrides the reproduce() method and returns a Dog object. This is possible because Dog is a subclass of Animal, so a Dog object can be treated as an Animal object.

The covariant return type allows us to write more specific code in the subclass without breaking the superclass contract. In other words, the subclass can return a more specific type, but it can still be used wherever the superclass is expected.

It’s important to note that covariant return type only applies to the return type of the method, and not to its parameters or access modifiers.

Share