Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

knb book pgs 308-310 polymorphism con't.

 
Alfonso Harding
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On pg 308-309 it says that the following code

will print:
in the Animal version
.
but in the chart on page 310 the following code

will print:
Horse eating hay
.

My question is if both pieces are superclass references to a subclass object why is that the first one will call the superclass' method and the second calls the subclass's method?
 
Priyanka Chopda
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you plz give few lines of code to make things easier to understand?
-PC
 
Sudhakar Krishnamurthy
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look carefully...though both refer to the super class doStuff() is an overloaded function which is decided at the compile time based on the reference type, while eat() is overridden function and is decided at runtime based on the object type.
HTH
 
Ross Goldberg
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code...

The lines you mentioned were:
Animal animalRefToHorse = new Horse();
ua.doStuff(animalRefToHorse);
As Sudhakar said, note how this is a reference of type ANIMAL even though it refers to a horse object. Since there are two methods...one taking a horse REFERENCE and one taking an animal REFERENCE, it uses the one with the ANIMAL reference...in fact, if that block were not present, the new line would fail to compile on ua.doStuff(animalRefToHorse);
This is because overloading (which is what this is) looks at the argument references. Once IN the method, a call to a method on ua would use polymorphism IF there were methods in Animal that were overrided in Horse.
Overloading uses the object references, and overriding uses the object subject to visibility constraints in the declared type (for example, if an Animal has no sleep method but Horse does and you call an animalReferenceToHorse.sleep, it would fail.
I am actually at the EXACT same point in the book as your question referred to (p. 313 to be exact).
Ross
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic