Draft Spec for Second Preview of Flexible Constructor Bodies (JEP 482)

Stephan Herrmann stephan.herrmann at berlin.de
Thu Jul 11 11:01:14 UTC 2024


I played a bit with Dan's example:

Am 30.05.24 um 06:39 schrieb Dan Smith:
> [...] 
> To clarify the model: yes, this rule was intentionally removed. It becomes very 
> complicated if you want to make rules about which enclosing instances exist or 
> don't exist based on positioning within a constructor. Example:
> 
> class C1 {
>      C1() {
>          super();
>          class C2 { // not early for C1
>              C2() {
>                  class C3 { // early for C2
>                      C3() {
>                          super();
>                          class C4 { // not early for C3
>                              ...
>                          }
>                      }
>                  }
>                  super();
>              }
>          }
>      }
> }
> 
> Does C4 have a 1st enclosing instance? Yep. 2nd? Maybe no? 3rd? It better...

I slightly extended it to this to make it testable:

class C1 {
    String f1 = "f1";
    C1() {
       super();
       System.out.print(f1);
       class C2 { // not early for C1
          C2() {
             System.out.print(f1);
             class C3 { // early for C2
                String f3 = "f3";
                C3() {
                   super();
                   System.out.print(f1);
                   class C4 { // not early for C3
                      C4() {
                         System.out.print(f3);
//                      System.out.print(f1);
                      }
                   }
                   new C4();
                }
             }
             super();
             new C3();
          }
       }
       new C2();
    }
    public static void main(String... args) {
       new C1();
    }
}

Using javac from build 23-ea+30-2323 this compiles fine and prints "f1f1f1f3".

When, however, I enable the innermost access to f1, javac complains:

   error: no enclosing instance of type C1 is in scope

Is this a bug, or am I missing some subtlety from the spec?

Please see that field f1 is accessible at all levels of nesting (because C1.this 
is fully initialized), so why should a class even in the *epilogue* of C3() not 
be able to read this field, when right before the class declaration it was 
accessible?

thanks,
Stephan


More information about the amber-spec-experts mailing list