Why can't an inner class use static initializer?

后端 未结 3 1914
陌清茗
陌清茗 2021-01-13 07:19

Quoth JLS #8.1.3:

Inner classes may not declare static initializers (§8.7)......

This is demonstrated as such:<

3条回答
  •  无人共我
    2021-01-13 07:43

    There's a contradiction by definition:

    From JLS §8.1.3:

    A statement or expression occurs in a static context if and only if the innermost method, constructor, instance initializer, static initializer, field initializer, or explicit constructor invocation statement enclosing the statement or expression is a static method, a static initializer, the variable initializer of a static variable, or an explicit constructor invocation statement (§8.8.7).

    ...

    When an inner class (whose declaration does not occur in a static context) refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used.

提交回复
热议问题