Originally posted by Rajitha Murthy:
The output of the following code is 'A'.But if
we'll change m1's signature in all the classes to no argument method then output will be 'C'.why?
Clearly, the differnce between
overloading and
overriding.
The initial situation is a clear case of overloading, because the method arguments are different, e.g. void foo(int i) and void foo(String s). In case of overloading the method executed is determined at compile time based on the type of the reference. That is, the type of c1 is A and your program prints 'A'.
Now when you change all signatures to be equal then we have a case of overrriding! A first declares m1, B's m1 overrides A's and C's m1 overrides B's. And the fun thing with overriding is that method executed is determined at run-time (by the JVM). So which method is executed is based on the class the object belongs to. That is, the class the object referenced by c1 belongs to is C, so you program prints 'C'.
[ April 20, 2006: Message edited by: Dick Eimers ]