Java › Inner Classes & Anonymous Classes
What is a local class's access to effectively-final local variables, and how does this same rule (and the underlying reason for it) apply identically to anonymous classes and lambdas?
IntermediateAnswer
Both local classes and anonymous classes can access local variables from their enclosing method scope, but ONLY if those variables are effectively final (never reassigned after initialization) -- this is the exact same rule and underlying reason discussed for lambda variable capture: since the local/anonymous class instance might outlive the method call that created it (e.g., stored and invoked later on a different thread), the compiler captures a fixed COPY of each accessed local variable's value at creation time rather than a live reference to the original variable, and permitting reassignment after that copy was made would create confusing, ill-defined semantics about which value the class 'sees'.
public Runnable makeRunnable() {
int count = 5;
// count = 10; // if uncommented AFTER the class below references count, COMPILE ERROR
class LocalTask implements Runnable {
public void run() { System.out.println("Count was: " + count); } // captures count's value
}
return new LocalTask();
}Real-world example A background task implemented as a local class captures a loop variable's value at the exact moment the task was created, correctly reflecting each individual task's specific captured value even though the enclosing loop continues iterating and would have moved to entirely different values by the time each task actually executes later.