aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes knb book pgs 308-310 polymorphism con't. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "knb book pgs 308-310 polymorphism con Watch "knb book pgs 308-310 polymorphism con New topic
Author

knb book pgs 308-310 polymorphism con't.

Alfonso Harding
Ranch Hand

Joined: Feb 09, 2002
Posts: 35
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

Joined: Jul 22, 2003
Posts: 112
Can you plz give few lines of code to make things easier to understand?
-PC
Sudhakar Krishnamurthy
Ranch Hand

Joined: Jun 02, 2003
Posts: 76
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

Joined: Jul 09, 2003
Posts: 63
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: knb book pgs 308-310 polymorphism con't.