posted 24 years ago
Paul- I think you're using a different definition of "hiding" than the one used in the JLS. "Hiding" can apply to variables and to static methods, but not to non-static methods - those can only be overridden (or overloaded, but that's something else). In your example speak() in Calf overrides speak() in Cow, period. It doesn't matter what the reference type of the variable c is, because the speak() method will be looked up at run time using the type of the object which c references - a Calf in this case.
For an example of hiding, you could make both speak() methods static. Then of course there it would make a difference what type c was declared as.
A general distinction between overriding and hiding: with overriding, if you have an instance of the overriding class, there is no way you can use it to access the overridden method (except from within the code for the overriding class itself, using super.methodName()). It doesn't matter if you try to cast the instance to its superclass - the overriding method will still be called:
<code><pre> Calf c = new Calf();
((Cow) c).speak();</pre></code>
The cast to Cow is ineffective in this case - speak() in Calf is still the one that will be called.
However, in the case of hiding, it is always possible to access a hidden method or variable by casting or otherwise using the appropriate class in the first place. In the above example, if speak() were declared static in both classes, then ((Cow) c).speak() would successfully invoke the hidden speak() method from class Cow. Of course, it would have been more direct to just call Cow.speak() in this case anyway - but the point is, the hidden method is accessible. Similarly, it is possible to access hidden variables in much the same way.
Looking back at psethura's list, I think it's pretty much accurate. One section I'd edit somewhat:
1. You cannot override or hide an instance method with a static method.
2. You cannot override or hide a static method with an instance method.
3. An overriding or hiding method must have the same return type.
3.5. An overriding or hiding method can't throw any checked exceptions not previously declared.
4. public method can be overridden or hidden only by public access
5. protected method can be overridden or hidden by public or protected.
6. Default access can be overridden or hidden by public, protected, or default access
"I'm not back." - Bill Harding, Twister