• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method override and covariant returns  RSS feed

 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, on the OCA book page 248 the 4th rule of overriding says that
if a method returns a value it must be the same or a subclass of the method in the parent class, known as covariant return types
.
On the same page there is an example:

Of course this doesn't compile and the book says that the reason is that the return type of the method in the child class isn't equal or a subclass of the method in the parent class. OK, that's cool.
But then on another book, there's this question:
What will be the result of this code?





Now, I answered that it will print 2 because a byte can fit in a short, but apparently it doesn't compile because this covariant rule is only valid when the return statement doesn't return a primitive. I'm not sure this in the OCA book though!
 
praveen kumaar
Ranch Hand
Posts: 450
22
Android Chrome Eclipse IDE Google App Engine Java Notepad Oracle Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Though it is not mentioned in your OCA book,it is mentioned well in java language specification-here it is--->JLS-8.4.5 , JLS-8.4.8.3.
even, suppose you convert them as-
"short----->Short & byte----->Byte"
still covariant return type will not hold because they don't obey a IS-A relationship i.e.their is no any inheritence b/w the 2 beside the fact that they both extends the Number class.
 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So if it's not in the OCA book, does it mean that it won't be in the exam?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!