What is covariant return types in Java?

Before JDK 5.0, it was not possible to override a method by changing the return type. When we override the parent class method, the name, parameter type, and return type of the overridden method in the subclass must be exactly the same as the parent class method. Overriding methods are considered to be invariant to the return type.

Covariant return types

Starting from Java 5.0, overriding methods in subclasses can have different return types, but the return type of the subclass should be a subtype of the return type of the parent class. Override methods have become variants in terms of return types.

The covariant return type is based on the Liskov substitution principle.

The following is a simple example to understand covariant return types with method coverage.

In Java, a method's return type specifies the type of value that the method returns. With covariant return types, a method in a subclass can override a method in its superclass to return a subtype of the return type declared in the superclass method.

In other words, if a superclass has a method that returns a specific type, and a subclass overrides that method, the subclass method can return a subtype of that type. This means that the subclass method can be more specific about the type it returns than the superclass method.

For example, consider a superclass called Animal that has a method called getSound() that returns a String: 

 

public class Animal {
    public String getSound() {
        return "Unknown sound";
    }
}

Now suppose we have a subclass called Dog that overrides the getSound() method: 

 

public class Dog extends Animal {
    @Override
    public String getSound() {
        return "Woof";
    }
}

Because the Dog class overrides the getSound() method and returns a more specific type (a String that represents a dog's bark), this is an example of covariant return types in Java.

Covariant return types can make code more flexible and expressive by allowing subclasses to return more specific types without breaking existing code that relies on the superclass method's return type.

Submit Your Programming Assignment Details