• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is Covariant Return ?

 
pradeep rajkumar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is meant by covariant return, in java programming ?
Can anyone please explain it with an example ?!!
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's when you override a method, while changing the return type. You can do this as long the overridden return type is more specific.

For example:
 
pradeep rajkumar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So if it is instantiated like the below code,

getLatestAddition() function in the animal class will be overrided right ??!!
 
Matthew Brown
Bartender
Posts: 4567
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, if you call obj.getLastestAddition() you'd call the version in TigerSanctuary.

But that's just normal overriding/polymorphism. The real difference with a covariant return is when you don't use the superclass reference type. If we override getLatestAddition() with the same return type (Animal) then we'd do this:
or this:

Whereas with the covariant return, we can do this:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic