Covariant return type in Java


Covariant return type is a feature introduced in Java 5 that allows a subclass method to return a more specific type than the type returned by the overridden superclass method. In other words, the return type of an overridden method in a subclass can be a subtype of the return type of the original method in the superclass.

Here's an example to illustrate this concept:

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

In the above example, the `Dog` class overrides the `getAnimal()` method of its superclass `Animal`. The return type of the overridden method in the `Dog` class is `Dog`, which is a subclass of `Animal`. This is allowed because `Dog` is more specific than `Animal`.

Covariant return types are useful when working with polymorphism, especially when dealing with class hierarchies and inheritance. They allow you to write more concise and expressive code by eliminating the need for type casting in certain situations.


Clear any Java Interview with our Study Notes

Are You Good enough in Java?


Need any Help?

Hot Deals ends in

Earn Money While You Sleep. Join Now to avail Exclusive Bonus

Technical Quiz:

Search Tags