aspose file tools*
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: 4422
    
    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: 4422
    
    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:
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: What is Covariant Return ?