Surender Thakran
Surender Thakran

Reputation: 684

static method redefining rules

I know it is a pretty beaten topic here but there is something i need to clarify, so bear with me for a minute.

Static methods are inherited just as any other method and follow the same inheritance rules about access modifiers (private methods are not inherited etc.)

Static methods are not over-ridden they are redefined. If a subclass defines a static method with the same signature as one in the superclass, it is said to be shadowing or hiding the superclass's version not over-riding it since they are not polymorphic as instance methods.

The redefined static methods still seem to be following some of (if not all) of the over-riding rules.

Firstly, the re-defined static method cannot be more access restricted than the superclass's static method. Why??

Secondly, the return types must also be compatible in both the superclass's and subclass's method. For example:

class Test2 {
    static void show() {
        System.out.println("Test2 static show");
    }
}

public class StaticTest extends Test2 {
    static StaticTest show() {
        System.out.println("StaticTest static show");
        return new StaticTest();
    }

    public static void main(String[] args) {
    }

}

In eclipse it shows an error at line at: The return type is incompatible with Test2.show() Why??

And Thirdly, are there any other rules that are followed in re-defining static methods which are same as the rules for over-riding, and what is the reason for those rules?

Thanx in advance!!

Upvotes: 3

Views: 1218

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234807

The requirements for hiding of static methods is spelled out in detail in §8.4.8.3 of the Java Language Specification. By and large, it's the same as for instance methods:

  1. The return type of the hiding method (in the subclass) must be assignment-compatible with the return type of the hidden method (in the superclass).
  2. The access modifier of the hiding method must be no more restrictive than that of the hidden method.
  3. It is an error for a method m in class T to have the same signature after erasure as another method n that is accessible in T unless the signature of m before erasure is a subsignature of method n.
  4. There are restrictions on the throws clauses of methods that hide, override, or implement other methods that are declared to throw checked exceptions. (Basically, the hiding method cannot be declared to throw checked exceptions that are not declared in the hidden/overridden/implemented method.)

I think that's it, but see the JLS for more details. The JLS does not explain the rationale for these rules, but most of them seem intended to prevent problems with polymorphism. You want a subclass to be usable wherever a parent class is being used.

Upvotes: 7

Related Questions