Java static imports

前端 未结 4 1252
借酒劲吻你
借酒劲吻你 2021-02-01 04:25

Just by experiment I discovered that Java non static methods overrides all same named methods in scope even at static context. Even without allowing parameter overloading. Like<

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 04:43

    It is not an override. If it did work, this.toString() would still access the method of A instead of Arrays.toString as would be the case if overriding had occurred.

    The language specification explains that static imports only affect the resolution of static methods and types:

    A single-static-import declaration d in a compilation unit c of package p that imports a field named n shadows the declaration of any static field named n imported by a static-import-on-demand declaration in c, throughout c.

    A single-static-import declaration d in a compilation unit c of package p that imports a method named n with signature s shadows the declaration of any static method named n with signature s imported by a static-import-on-demand declaration in c, throughout c.

    A single-static-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

    • any static type named n imported by a static-import-on-demand declaration in c.
    • any top level type (§7.6) named n declared in another compilation unit (§7.3) of p.
    • any type named n imported by a type-import-on-demand declaration (§7.5.2) in c. throughout c.

    Static imports do not shadow non-static methods or inner types.

    So the toString does not shadow the non-static method. Since the name toString can refer to a non-static method of A, it does cannot refer to the static method of Arrays and thus toString binds to the only method named toString that is available in scope, which is String toString(). That method cannot take any arguments so you get a compile error.

    Section 15.12.1 explains method resolution and would have to have been completely rewritten to allow shadowing of unavailable method names within static methods but not inside member methods.

    My guess is that the language designers wanted to keep method resolution rules simple, which means that the same name means the same thing whether it appears in a static method or not, and the only thing that changes is which are available.

提交回复
热议问题