| Author |
Java RTTI Question - I think!
|
Martin Rennix
Ranch Hand
Joined: Sep 30, 2001
Posts: 34
|
|
Have pity on a poor C programmer trying to learn OOP! Say I have the following code: <pre> class Animal { public void print(){ System.out.println("I am an animal"); } } public class AnimalTest { public static void main(String[] args) { Animal a = new Animal(); Object obj = a; a.print(); //prints "I am an animal" obj.print(); //fails compile with "cannot resolve symbol" System.out.println(obj.getClass().getName()); // prints "Animal" } </pre> Here's where I'm confused. Variable "obj" is assigned an "Animal" but I can't call obj.print(). Why not? Doing a "getClass" on obj returns "Animal", so how come obj can't resolve the print() method in Animal? I'm sure I'm making a basic error here, I'd love to hear a simple explanation! Martin
|
 |
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
|
|
1) Since Object does not have a print() method, the print() method in Animal is not an overriding method. 2) The compiler matches methods to reference types. It finds no method named print() for the Object reference type. So it never gets to the "runtime binding". If you cast thus: Animal b = (Animal)obj ; b.print(); it will work because the compiler sees that 'a' and 'b' are Animals and matches them to the print() method in the Animal class.
|
JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
|
 |
Martin Rennix
Ranch Hand
Joined: Sep 30, 2001
Posts: 34
|
|
|
Thanks Marilyn!
|
 |
 |
|
|
subject: Java RTTI Question - I think!
|
|
|