wood burning stoves*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Polymorphic calls" Watch "Polymorphic calls" New topic
Author

Polymorphic calls

Clay Chow
Ranch Hand

Joined: Nov 09, 2008
Posts: 35
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

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
Sheriff

Joined: Oct 13, 2005
Posts: 37900
    
  22
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: http://aspose.com/file-tools
 
subject: Polymorphic calls
 
Similar Threads
method types in Generics
Compilation Error when using Generics
Generics doubt.
Doubt About Generic
Generics Doubt