I understand why an enum constructor cannot access static fields and methods within the enum itself, and why the same is allowed for in classes. Se for an example the following code,
import java.util.ArrayList;
import java.util.List;
public enum Foo {
A("Some string"),
B("Some other string"),
;
static List<String> list = new ArrayList<>();
Foo(String description) {
list.add(description);
}
}
This code causes a compile-time error, illegal reference to static field from initializer.
Relevant background
The enum constructor is called before the static fields have all
been initialized. In the above example this means that list is not yet initialized. This is because static fields are initialized in textual
order (section 12.4.2)
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
(emphasis mine)
and since the enum values themselves always precede any other
fields, including static fields, they are not available to the
enum constructor, i.e. no static fields may preceed the enum
values A, and B.
Question
However, and here is my question, why is it that a "private" (enclosed inside a class) enum
can access static fields of its enclosing class,
regardless of whether or not the enum appears before --- or ---
after the static fields? In particular, where in the Java-specification is this specified?
See the below code for reference
import java.util.ArrayList;
import java.util.List;
public class Bar {
static List<String> first = new ArrayList<>();
enum Baz {
A("Some string"),
B("Some other string"),
;
Baz(String description) {
// Can access static fields from before the enum
first.add(description);
// Can access static fields from _after_ the enum
second.add(description);
}
}
static List<String> second = new ArrayList<>();
}