File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Return type problem 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 "Return type problem" Watch "Return type problem" New topic

Return type problem

Rajesh k Jha
Ranch Hand

Joined: May 10, 2009
Posts: 72
class Animal{}
class Gerbil extends Animal{}
class Vet{

Can somebody explain how check covariant return type as what i understand is
In line 7
Gerbil is the subclass so covariant return type is ok..but what to chek in the return type as return tyoe in line 7 is "return new Gerbil()" How does return type(return new Gerbil()) is related to "Gerbil go()"

as it says line 9 is wrong? I am a bit confused, so please give example to make me understand
Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

If you take covariant return types out of your mind, will line 9 compile?? The answer is no as the method returns Gerbil so it can't return Animal class instance as Animal is super class of Gerbil. So for covariant return types, you just need to know that the return type of an overriding method can only be the save type as the overridden method or a sub-type (you know this). Other than that what you can return from the covariant method is as simple as a normal method...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Rajesh k Jha
Ranch Hand

Joined: May 10, 2009
Posts: 72
Thanks Ankit..I know it was simple but confusion lies everywhere..
Thks for clarification
I agree. Here's the link:
subject: Return type problem
It's not a secret anymore!