top of page

Covariant return type

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


MiIT Logo

Company

Contact Us

905-487-4880 

5160 Explorer Dr #34, Mississauga,ON L4W 4T7

646-713-5711

4466 Buttonwood Ln Lilburn, GA 30047

262 Chapman Rd, STE 240 Newark DE 19702

Stay up to date on the latest from MiIT

  • Instagram
  • Facebook
  • http://linkedin.com/company/miittechnologies/about/
  • Whatsapp

© All Content MiIT Technologies Inc.2019 - 2024. All rights reserved.

bottom of page