aspose file tools*
The moose likes Beginning Java and the fly likes Dynamic Polymorphism: new method in subclass Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic Polymorphism: new method in subclass" Watch "Dynamic Polymorphism: new method in subclass" New topic
Author

Dynamic Polymorphism: new method in subclass

Darren Johnston
Greenhorn

Joined: Jan 10, 2002
Posts: 4
I'm trying to create an dynamic object at runtime. In creating an object of the superclass reference and then reassigning the value of the subclass reference I receive this error during compile:
app.java:37: cannot resolve symbol
symbol : method doThis ()
location: class a
aref.doThis();
^
1 error
What is wrong with this code?

(edited by Cindy to format code)
[ January 24, 2002: Message edited by: Cindy Glass ]
Roy Ben Ami
Ranch Hand

Joined: Jan 13, 2002
Posts: 732
this is the nature and basic concept of casting and polymorphism.
basically because aref is a refrence to class A it always will check first in class a for the method and variables. (even if it actually points to object of class B).
if it finds a method there like print() then IF there is an overriden version of print in class B it will perform the print of class B (if there wasnt one he would have performed the one in class A).
however, if u define new function OR variables in the class that inherit from A (like doThis() for example) then the compiler gets stuck.remember that the compiler thinks aref refers to class Aso he doesnt find any doThis() there.
in order to tell the compiler that he actually points to class B in this case we need to do casting like this:
((B)aref).doThis();
now we tell the compiler to look at aref as a refrence to class B in this sentence so he will perform the action!
Tony Jackson
Ranch Hand

Joined: Feb 23, 2001
Posts: 45
At the point when you call doThis( ), aref is a reference to a "b" object. Since b defines the method doThis( ), you should be able to call it - and you can, but not simply by the call aref.doThis( ) - the compiler doesn't know that aref is a "b" object - all it knows is that aref is a reference to an "a" object - so it complains that "a" doesn't have a method doThis( ).
You could cast it like this:
((b) aref).doThis
Tony
Darren Johnston
Greenhorn

Joined: Jan 10, 2002
Posts: 4
Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Dynamic Polymorphism: new method in subclass
 
Similar Threads
K&B SCJP6 Chapter 3- Q11 a GC question
help needed on Inner classes program
Casting problem
Class Cast related query
fwd or backward ,don't know which reference??