Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java RTTI Question - I think!

 
Martin Rennix
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Martin Rennix
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Marilyn!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic