I have an abstract superclass animal. Dog,Cat,Wolf,Hippo Lion are subclasses of this superclass. each subclass has its own overloaded roam() method
animals s=new Wolf(); animals t=new Hippo();
I then call a method on each of these:
Since the compiler decides whether you can call a method based on the reference type,not the actual object type,how does the compiler know which method to call? Does it traverse the inheritance tree? If yes ,how? [ May 20, 2006: Message edited by: Stephan Norwood ]
Stephan, The compiler knows that the Animal class has a method roam. This means that all subclasses must also have this method. Note that this method has the same signature so it is overriden. (overloading is when you add/change parameters to change the method signature.)
So the compiler knows it has to be legal to call roam(). It doesn't know which one and it doesn't need to. That's where polymorphism steps in. It's the job of the JVM to call the appropriate roam() method based on the subclass type.
Stephan, just to add to the previous reply... Your last 3 questions about traversing the inheritance tree:
Your example, where Wolf is a subclass of animals:
animals s=new Wolf(); s.roam();
The JVM traverses the inheritance tree. If Wolf overrides the roam method, then that's the method that will be used. If Wolf does not override the method, then the JVM will walk up the inheritance tree to find the first superclass with that method in it.
The compiler makes sure that Wolf is a subclass of animals, and the compiler lets you call s.roam() because roam() is a method in class animals. It doesn't know/care that s is really of type Wolf, or whether class Wolf overrides the roam() method. (This is because s might be different subclasses, depending on how you write your code and what happens at runtime). The compiler lets you call roam() on s because it knows that roam() is at least defined in class animals, then every subclass of animals has to either a) inherit the method, or b) override it. Thus, Wolf has a roam() method.
Does this give you a better idea of the mechanism?