The difference is creating an anonymous subclass within an instance's context versus a static context. Compare:
public class InnerClasses {
int pack;
private int priv;
static private int stat;
private class NotStatic {
{
pack = 1;
priv = 1;
stat = 1;
}
}
private static class IsStatic {
{
pack = 1; // Static member class not tied to outer instance
priv = 1; // Ditto
stat = 1;
}
}
public void instanceMethod() {
InnerClasses a = new InnerClasses() {
{
pack = 1;
priv = 1;
stat = 1;
}
};
}
public static void main(String[] args) {
InnerClasses s = new InnerClasses() {
{
pack = 1;
priv = 1; // Anonymous subclass in static context
stat = 1;
}
};
}
}
The lines with comments do not compile. The ones for IsStatic
are simple enough to understand, but the difference between the anonymous classes in instanceMethod
and the static main
is more subtle.
Note that private
really has the effect of "visible only within the enclosing top-level class", and not "visible only within that class". (As I recall, the latter is the actual mechanism at the JVM level, and the way to get the former effect is by synthesizing accessor methods.) That's how NotStatic
can access priv
.
So apparently the difference is that when creating an anonymous subclass in a static context, it is not considered "enclosed". Someone more familiar with the JLS might be able to clarify.