This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hello. Can static methods be overridden? I wrote simple code to test. Given that the declaration type of the reference and the object are both of the subclass type: <subclass type> var = new <subclass type>(), the static method was overridden from its superclass. However, using dynamic method binding where: <superclass type> var = new <subclass type>(), the static method from the superclass was called instead of the one in the subclass. For instance methods. The overriding methods in the subclass during dynamic method binding, as expected, was called. I first had the impression if you can inherit it, then you can override it. Is this true for static methods? Here's the code i used:
Static (class) methods are not overridden, they are hidden or redefined in the subclasses. Polymorphism doesn't apply to static members, they are bound statically at compile time. The class type determines which static method will be called. Here's a set of valuable rules from JLS to follow while hiding methods:
22.214.171.124 Requirements in Overriding and Hiding If a method declaration overrides or hides the declaration of another method, then a compile-time error occurs if they have different return types or if one has a return type and the other is void. Moreover, a method declaration must not have a throws clause that conflicts (�8.4.4) with that of any method that it overrides or hides; otherwise, a compile-time error occurs. In these respects, overriding of methods differs from hiding of fields (�8.3), for it is permissible for a field to hide a field of another type. The access modifier (�6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail: CLASSES Inheritance, Overriding, and Hiding 8.4.6 � If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs. � If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs. � If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs. Note that a private method cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass.