Can someone explain this to me? my question is regarding the line 'cc.test(cg)'? How come it prints out "in child" instead of "in grandkids"? I understand that the reference type for cg is grandkids and grandkids is a subclass of child. Thanks in advance for your help.
[ August 19, 2005: Message edited by: Barry Gaunt ]
Hi, I guess that's because your child class extends parent so it has only 2 methods : void test(parent pp) void test(child cc)
but there is NO test method that takes a grandkid class as an argument. As grandkids extends child, a grandkids is a child. Then when you call the cc.test(gc), the gc is considered as a child, that's why it prints out "in child", because it's the test(child cc) method that is executed. I hope it was clear... Sebastien
Which version of overloaded method is called is decided at compile time and the same method is called at run time (remember in case of overriding, runtime object type decides which version of overriding method is called).
Based on that, cc is of type Child and cc.test(cg) in the form of
child . test (grandkids)
but child class doesn't have a test method which accepts grandkids argument it only has the following two test methods (and it is clear that test method is overloaded method in child class)
test(parent) inherited from parent class test(child) declared in child class itself
now cg is of grandkid and grandkid 'is a' child. So, at compile time overloaded version of test(child) method from child class is the most specific method and this is what gets called even at run time.
Bottom line is, overloaded methods won't be further resolved based on runtime type object at runtime.
In your code, it doesn't matter what the reference is pointing to after the compiler has decided which overloaded method to call, since you don't actually use it.
As the others have said, since Child has no test() method that accepts a Grandkids object, but since Child's test() does accept another Child (which Grandkids can be converted to), then that's the method that gets called: Child.test().
Once inside Child.test(), you never actually use the Grandkids reference. You just output a simple string: "in child".
Try adding this code inside your Child class:
That will give you the result you expect because it gives Grandkids something to override. [ August 22, 2005: Message edited by: Ryan Kade ]