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

Disallow enclosing instances for local classes in constructor prologues

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 23
    • None
    • tools
    • b18
    • generic
    • generic

      During the work for JDK-8194743 it was noticed that the compiler was currently allowing a local class declared in a constructor prior to super() (previously defined as a "static context", now called the "constructor prologue") to have enclosing instances. For example:

        import java.util.concurrent.atomic.*;
        public class Test extends AtomicReference<Object> {
        
          public Test() {
              super(switch (0) {
                  default -> {
                      class Local {
                          { System.out.println(Test.this); }
                      }
                      yield null;
                  }
              });
          }
        }

      According to JLS 21 §15.9.2, class Local should not have an immediately enclosing instance, so the above program should not compile.

      Of course, prior to JDK-8194743, the only way to declare a local class prior to super() was to do something very contrived like the above example.
      Still, in order to not change existing compiler behavior in such a scenario, this bug was not addressed as part of JDK 22.

      The new term "constructor prologue" describes the constructor code region prior to super(), but the same rules apply, i.e., local and anonymous classes declared therein should not have any immediately enclosing instance.

      The compiler properly enforces this for anonymous classes, but not for local classes.

            acobbs Archie Cobbs
            acobbs Archie Cobbs
            Votes:
            1 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: