Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return types allowed

 
John Lerry
Ranch Hand
Posts: 145
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given this code:



the correct answers are:

- If uncommented line 7 will compile
- If uncommented line 8 will compile
- If uncommented line 10 will compile
- Only one of the lines from 7 to 10 can be uncommented at a time and still compile



regarding the possible return types I have no doubts as to call a method that has the return type of the type of a subclass can ALSO return the type of the superclass. Is that correct?

The doubt I have that ONLY a line 7 to 10 can be uncommented without creating errors in compilation.

Why there would be a mistake in the case of multiple lines without comment?
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
regarding the possible return types I have no doubts as to call a method that has the return type of the type of a subclass can ALSO return the type of the superclass. Is that correct?

No, that's not correct at all!

If the return type of your method is a subclass, you can only return instances of the subclass and its subclasses, not superclass(es)' instances. An example to illustrate:The create1 method fails, because Object IS-NOT-A Animal, you can only return Animal (create2) or its subclass(es) (create3).

The doubt I have that ONLY a line 7 to 10 can be uncommented without creating errors in compilation.

Why there would be a mistake in the case of multiple lines without comment?

That's an easy one and also well explained in K&B7: if you would uncomment more than 1 line at the same time, you would have illegal overloaded methods and that's confusing the compiler hence the compiler error. Assume we uncomment line 7 and 8, the code of the SmallAnimalVet class would be:So this class has 2 methods with exactly the same name go and also exactly the same (empty) parameter list. If you know the rules for valid overloaded methods, you'll know this is not allowed! If you can't remember the rules for overloading methods, you should definitely refresh this part of the study guide, because knowing the rules for overloading and overriding methods are really, really, really important! If you don't know them well, you'll probably fail the exam!

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic