Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8025762

8.3.3: Clarify that a field cannot be referenced in its own initializer

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 9
    • 1.2.0, 5.0, 7, 8
    • specification

      The rules in 8.3.2.3 (8.3.3 in JLS 8) are designed to prevent circularity in the initialization of fields. This is accomplished by requiring that most references to a field in a field initializer (or initializer block) must happen _after_ the declaration of the field. But, strangely, I can't find an explicit rule prohibiting the simplest circularity of all: a field that refers to itself.

      class Foo { int i = i+1; } // error in javac

      JLS 1 8.3.2.2 said "A compile-time error occurs if an initialization expression for an instance variable contains a use by a simple name of that instance variable or of another instance variable whose declaration occurs to its right (that is, textually later) in the same class." And, "int k = k+1;" was exemplified as an error "because the initialization of k refers to k itself."

      JLS 2 rewrote these sections and no longer explicitly prohibited a field from being used in its own initializer.

      ---

      Suggested text:

      Use of instance variables whose declarations ***contain or*** appear textually after the use is sometimes restricted, even though these instance variables are in scope. Specifically, it is a compile-time error if all of the following conditions hold:

      • The declaration of an instance variable in a class or interface C ***either contains or*** appears textually after a use of the instance variable;

      • The use is a simple name in either an instance variable initializer of C or an instance initializer of C;

      • The use is not on the left hand side of an assignment;

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

      [May also want to update some informal descriptions of this rule appearing elsewhere in 8.3.2.]

            abuckley Alex Buckley
            dlsmith Dan Smith
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: