The reason for this behaviour is related with how
Java implements the inheritance. When an object of subclass is created it also creates object of the super class and hence a Method table of the super class is also created. So once we start creating an object, the method table will contain entries for the super class but if you override a method in the sub class then the method table will override the superclass's method with subclass's method. So the object no longer contains the entry for super class's method.
As it is little bit confusing let me try to use an example
class SuperGrand
{
void PrintMe();
}
class Super extends SuperGrand
{
void PrintMe();
}
class Sub extends Super
{
void PrintMe()
}
So when object of Sub is created it will first create an object of Super. Super will try to create an object of SuperGrand before it gets created. So the order of creation of objects would be like
step1. SuperGrand
step2. Super
step3. Sub
So the method table at different steps will be
step1.
SuperGrand.PrintMe()
step2.
Super.PrintMe()
step3
Sub.PrintMe()
So as you can see everytime you override a method it changes the Method table. It's the Method table owned by the object so irrespective of the way you cast it you are looking at the same method table in the object and you have overridden the methods available in that Method table.
Another thing to note here is that when you cast an object it limits the method table entries that you can access depending on the type of object. That's why following code won't work
class Super{}
class Sub extends Super()
{
public static void Main(
String [] args)
{
Sub objSub = new Sub();
((Super)objSub).InvisibleToSuper(); -> This won't compile.
}
public InvisibleToSuper()
{
}
}
I hope I was able to explain it. I would appreciate a correction if I am wrong. I am not sure if Method Table is the right
word for it, but my intention was to explain my understanding and Method Table seemed to be a good name to explain.
hope it helps
Gaurav Mantro
[This message has been edited by Gaurav Mantro (edited February 02, 2001).]