A compile-time error occurs if an instance method overrides a static method. In this respect, overriding of methods differs from hiding of fields (�8.3), for it is permissible for an instance variable to hide a static variable. ... If a class declares a static method, then the declaration of that method is said to hide any and all methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. A compile-time error occurs if a static method hides an instance method. In this respect, hiding of methods differs from hiding of fields (�8.3), for it is permissible for a static variable to hide an instance variable. Hiding is also distinct from shadowing (�6.3.1) and obscuring (�6.3.2). A hidden method can be accessed by using a qualified name or by using a method invocation expression (�15.12) that contains the keyword super or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields.
Corey, So overriding a static method is illegal but overriding a static method by another static method with similar arg list and return type is legal, Is my understanding correct here??
Joined: Dec 20, 2001
It is illegal to "override" an instance method with a static method with the same signature. It is legal to have a static method in the parent class and a static method with the same signature in the subclass. However, this is not overriding. This is called method hiding and they behave very differently. Let me explain with a couple examples. First let's look at the behavior of overriding. For this, we'll need two classes with an overridden method (which is, of course, an instance method, as only instance methods can be overridden).
As we have overridden this method, we use dynamic method binding in order to determine which method to invoke. As the run-time type of both s1 and s2 is Sub, the method doIt in Sub is invoked in either case. Now, let's use a pair of static methods. In this case the method in the subclass is said to "hide" the method in the superclass:
As you can see, we no longer use dynamic method binding in order to determine which method to invoke. Rather, the compile time type (rather than the tun time type) is used in order to determine which method should be invoked. As the compile time type of s1 is Super and the compile time type of s2 is sub, we invoke the doIt methods of Super and Sub, respectively. I hope that helps.