This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Originally posted by ARIJIT DARIPA: static methods are inherited
That's not an instance of inheritance, that's an instance of accessibility. Since both classes are in the same package, the static method is available to the Child subclass. Since Child is castable to Parent(), when the StaticMeth method is attempted to be invoked, the compiler first checks for a method of Child that matches it. It does not find that, so it checks the super class. It does find a method, but it is static. So, it uses the static shortcut. Saying c1.StaticMeth is equivalent to ((Parent)c1).StaticMeth(); This shortcut is then taken one step further and the result is Parent.StaticMeth(); Only non-static methods and variables are inherited, statics by definition cannot be inherited because they are only defined for the class or interface they are declared in. Just because you can access them from this sort of shortcut doesn't change this, it is a convienience, nothing more.
Ben, I think what needs to be noticed here is that, in your test program, your array reference was of type "parent" ( StaticParent parent = ).
When you assigne the three objects you set the array to one StaticParent, then one StaticExampleTest and finally one SaticParent. You then step through the array calling the method on each object. Now HERE is the important part.
Static methods are not inherited, per se. They can be replaced/substitiued. The thing to remember is that you get the method that goes with the reference type!!! So since your array type was StaticParent then, even thought the object was a StaticExampleTest itself, since the reference is StaticParent, StaticParent's version of the method will be called.
and see what happens.
This is like this because "a static method belongs to the class". In other words, when you have a Superclass - Subclass relationship between two classes and each class has a static method with the exact same name and signature, you get the version that goes with the type of the reference. Recall that a sataic can be called in one of two ways:
1) by the class (StaticParent.doStuff(); ) , or
2) by an instance reference, such as in your test code. But the version that you get is tied to the type of the reference, in the case of a static method. [ September 09, 2008: Message edited by: Bob Ruth ]
SCJP - 86% - June 11, 2009