How does a local or anonymous class defined inside a static method or static context differ from one defined inside an instance method, regarding what enclosing state it can access?
Short answer
A local or anonymous class defined within a STATIC method (or any static context) has no enclosing instance to implicitly reference at all (since a static method itself isn't associated with any particular instance), meaning it can only access the enclosing class's static…
Advertisement
AModel answer
A local or anonymous class defined within a STATIC method (or any static context) has no enclosing instance to implicitly reference at all (since a static method itself isn't associated with any particular instance), meaning it can only access the enclosing class's static members and any effectively-final local variables from that static method's own scope -- a local/anonymous class defined within a non-static (instance) method, by contrast, DOES have an implicit outer instance reference available, letting it additionally access the enclosing instance's non-static fields and methods, an important distinction that determines what's actually accessible from within the nested class depending on the enclosing context's own static-ness.
public class Outer {
private int instanceField = 1;
private static int staticField = 2;
public static void staticMethod() {
class StaticLocal {
void show() {
System.out.println(staticField); // OK: static context, static field accessible
// System.out.println(instanceField); // COMPILE ERROR: no outer instance available here!
}
}
}
}Real-world example
A utility factory method declared static that internally defines a local class implementing a callback interface can only reference the enclosing class's static configuration constants, not any instance-specific state, since being invoked as a static method means there's no particular Outer instance for the local class to implicitly associate with.
Likely follow-ups
- Why does a static nested class behave identically to a local class defined in a static context regarding outer-instance access, despite being declared differently?
- What compile error message specifically appears if you try to access an instance field from within a class defined in a static context?
Related topics