How come the output is "SuperClass SuperReturn doStuff()" when superFoo is actually pointing to a SubClass Object, that has an overridden implementation of doStuff(). Arnt all methods in Java virtual? How come it dosnt call the subclass implementation? If someone could clear this up for me I would be very happy.
If two methods have different argument lists -- if the types differ at all, even if, as in your case, one is a subclass of the other -- then there's no runtime polymorphism. The method is said to be overloaded, rather than overrridden. The compiler chooses which method to call based on the compile-time type of the arguments -- i.e., the types of any variables or literals passed to the method call.
It helps to think of a method as being characterized by a signature, which includes the name of the method and the number and types of the arguments. If the signatures of two methods differ, they might as well have different names -- there is no polymorphism. You get runtime polymorphism only if the signatures are identical.
Note that I did not include the return type as part of the signature. As you've been asking about in another thread, Java 5 allows covariant return types -- the return type of a method in a subclass can be a subtype of the return type of the method with the same signature in the parent class.
Originally posted by Mr. C Lamont Gilbert: Method calls are all determined at compile time. There is no "runtime polymorphism" of method calls.
Which object the method is called on is determined at runtime. But which method to call on said object is pre-determined.
Although I understand what you're trying to say, this really isn't the right way to say it. The object that the method is called on is always known -- it's the one in the variable on the left of the dot operator. It's not like the JVM searches around to find an object. What isn't known is which implementation of a polymorphic method will be used; that's what's determined at runtime.
The method signature is fixed at compile-time; which of several overloads is chosen by the compiler.
With other words, Java doesn't support covariant parameters.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus