The observed behavior is mandated by the Java Language Specification, in particular implicit access to fields of enclosing types, and the rule that private members are not inherited.
unqualified field access
A { public int get() { return i; } }
The spec mandates:
The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors.
This makes the expression i
somewhat ambiguous: Are we referring to the field of the enclosing instance, or the inner instance? Alas, the inner instance doesn't inherit the field:
Members of a class that are declared private are not inherited by subclasses of that class.
Therefore, the compiler concludes we mean to access the field of the enclosing instance - but being in a static block, there is no enclosing instance, hence the error.
field access through this
B { public int get() { return this.i; } },
The spec mandates:
When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.
Therefore, it is quite clear we want the field of the inner class, not the outer one.
The reason the compiler rejects the field access expression this.i
is:
Members of a class that are declared private are not inherited by subclasses of that class.
That is, a private field can only be accessed through a reference of the type that declares the field, not a subtype thereof. Indeed,
B { public int get() { return ((E)this).i; } },
compiles just fine.
access through super
Like this, super refers to the object the method was invoked on (or the object being constructed). It is therefore clear we mean the inner instance.
Additionally, super is of type E
, and the declaration therefore visible.
access through other field
D { public int get() { return D.i; } };
Here, D
is an unqualified access to the static field D
declared in E
. As it is a static field, the question of which instance to use is moot, and the access valid.
It is however quite brittle, as the field is only assigned once the enum object is fully constructed. Should somebody invoke get() during construction, a NullPointerException
would be thrown.
Recommendation
As we have seen, accessing private fields of other types is subject to somewhat complex restrictions. As it is rarely needed, developers may be unaware of these subtleties.
While making the field protected
would weaken access control (i.e. permit other classes in the package to access the field), it would avoid these issues.