File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Java RTTI Question - I think! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java RTTI Question - I think!" Watch "Java RTTI Question - I think!" New topic

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:
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"
// prints "Animal"
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!
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059
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 ;

it will work because the compiler sees that 'a' and 'b' are Animals and matches them to the print() method in the Animal class.

"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!
I agree. Here's the link:
subject: Java RTTI Question - I think!
It's not a secret anymore!