3

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!!

4

1 回答 1

7

Java 语言规范的第 8.4.8.3 节详细说明了隐藏静态方法的要求。总的来说,它与实例方法相同:

  1. 隐藏方法的返回类型(在子类中)必须与隐藏方法的返回类型(在超类中)赋值兼容。
  2. 隐藏方法的访问修饰符不能比隐藏方法的访问修饰符更严格。
  3. m类中的方法在擦除后与另一个可访问的方法T具有相同的签名是错误的,除非擦除的签名是 method的子签名。nTm n
  4. throws隐藏、覆盖或实现声明为抛出已检查异常的其他方法的方法的子句存在限制。(基本上,隐藏方法不能声明为抛出未在隐藏/覆盖/实现方法中声明的检查异常。)

我想就是这样,但请参阅 JLS 了解更多详细信息。JLS 没有解释这些规则的基本原理,但它们中的大多数似乎旨在防止多态性问题。您希望在使用父类的任何地方都可以使用子类。

于 2012-08-05T08:04:52.430 回答