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 ]
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!
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
Joined: Jan 10, 2002
subject: Dynamic Polymorphism: new method in subclass