This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes What is Covariant Return ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "What is Covariant Return ?" Watch "What is Covariant Return ?" New topic
Author

What is Covariant Return ?

pradeep rajkumar
Greenhorn

Joined: May 26, 2011
Posts: 10
What is meant by covariant return, in java programming ?
Can anyone please explain it with an example ?!!
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4541
    
    8

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

Joined: May 26, 2011
Posts: 10
So if it is instantiated like the below code,

getLatestAddition() function in the animal class will be overrided right ??!!
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4541
    
    8

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:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is Covariant Return ?
 
It's not a secret anymore!