This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What is Covariant Return ?  RSS feed

 
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: 4568
9
  • 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: 4568
9
  • 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:
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!