• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Java RTTI Question - I think!

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Marilyn!
reply
    Bookmark Topic Watch Topic
  • New Topic