• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Return type problem

 
Rajesh k Jha
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Rajesh k Jha
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ankit..I know it was simple but confusion lies everywhere..
Thks for clarification
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic