File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Polymorphic calls Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Polymorphic calls" Watch "Polymorphic calls" New topic

Polymorphic calls

Clay Chow
Ranch Hand

Joined: Nov 09, 2008
Posts: 35
I am studying for my SCJP and wrote this little bit of code to figure out how polymorphic calls work.

Which outputs:




why does line A1 not retrieve the instance value ? Even though at compile time, it reads the reference value, at runtime it should read the instance value.

Chad James

Joined: Mar 31, 2009
Posts: 1
Clay, I'm not sure why your code doesn't work the way you have written it but my limited experience with Polymoprhism usually deals with method calls. For instance if line A1 looked like this;

You would get your expected output. Which toString() method gets called depends on the type of o.
Ryan Beckett
Ranch Hand

Joined: Feb 22, 2009
Posts: 192
Polymorphism only applies to overridden methods. Each objects overridden toString() executes, but the instance variable that is referenced is always the one defined in the Fruit class. Polymorphism has absolutely nothing to do with instance variables, therefore the reference variable type decides which instance variable value is printed.
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

polymorphism is built off the relationship between classes, or inheritance. when you are using a class attribute, name in this case the subclass has to pass its name attribute to the super class, otherwise the class attribute will always be that of the class.

try this:

"If the facts don't fit the theory, get new facts" --Albert Einstein
Sagar kanchi
Ranch Hand

Joined: Oct 07, 2005
Posts: 50
Remember the following rules,

1) Variables are never overridden.
2) Variables are binded during compile time

Based on above, 'o' is casted to Fruit and no matter whether 'o' refers to Fruit or Apple or even another subclass of Fruit object at Runtime. Decision to access which variable was taken at compile time and at that time we ONLY know that that variable is of type Fruit because of the cast.

That's why this always prints 'Fruit'

System.out.println(( (Fruit) o).name);

Where there are more wonders there is less knowledge
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46367
It would have been better design to have all the fields private. Then the problem would never have arisen.
I agree. Here's the link:
subject: Polymorphic calls
It's not a secret anymore!