Why can my instance initializer block reference a field before it is declared?

后端 未结 5 513
無奈伤痛
無奈伤痛 2021-01-18 03:19

My understanding is that you cannot reference a variable before it has been declared, and that all code (including instance initializers) that is within the body of a class,

5条回答
  •  臣服心动
    2021-01-18 04:02

    From docs:

    8.3.2.3. Restrictions on the use of Fields during Initialization

    The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:

    • The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer
      of C.

    • The usage is not on the left hand side of an assignment.

    • The usage is via a simple name.

    • C is the innermost class or interface enclosing the usage.

    It is a compile-time error if any of the four requirements above are not met

    In this case, the usage is on the left hand side of the assignment, so it is not a compile-time error.

提交回复
热议问题