Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphic calls

 
Clay Chow
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am studying for my SCJP and wrote this little bit of code to figure out how polymorphic calls work.




Which outputs:

fruit
Apple
fruit
Apple
fruit
fruit


Expected:
Apple
Apple
Apple
Apple
fruit
fruit

Question:

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
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:


 
Sagar kanchi
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
 
Campbell Ritchie
Sheriff
Posts: 48409
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would have been better design to have all the fields private. Then the problem would never have arisen.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic