top of page

Covariant return type

Dimpal Lunagariya

Covariant return types in Java is a feature that allows a subclass to return a more specific type than what is declared in its parent class. This means that when you override a method in a subclass, the return type of the subclass can be a subtype of the return type of the superclass method. This can make it easier to use subclasses in polymorphic situations, as the client code doesn't have to perform type checks or casts.

For example, consider the following code:

class Animal

{

Animal getAnimal()

{

return this;

}

}

class Dog extends Animal

{

Dog getAnimal()

{

return this;

}

}

Here, the getAnimal() method of the Dog class returns an instance of Dog, which is a subtype of Animal. This is allowed because of covariant return types.

It's important to note that covariant return types are only applicable to reference types and not primitive types. Also, the return type of an overridden method must be a subtype of the return type of the superclass method, not just any type. This means that the return type must be compatible with the return type of the superclass method.

In conclusion, covariant return types can make code more readable and flexible by allowing a subclass to return a more specific type than what is declared in its parent class, making it easier to use subclasses in polymorphic situations

 
 
 

Recent Posts

See All

Comments


bottom of page