File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion 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

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?
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.
Ross Goldberg
Ranch Hand

Joined: Jul 09, 2003
Posts: 63
The code...

The lines you mentioned were:
Animal animalRefToHorse = new Horse();
As Sudhakar said, note how this is a reference of type ANIMAL even though it refers to a horse object. Since there are two taking a horse REFERENCE and one taking an animal REFERENCE, it uses the one with the ANIMAL 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).
I agree. Here's the link:
subject: knb book pgs 308-310 polymorphism con't.
It's not a secret anymore!