An anonymous inner class can read a local variable from its enclosing scope as long as that variable is never reassigned after the class is created, the same effectively-final rule lambdas follow.
int base = 10;
Runnable r = new Runnable() {
@Override public void run() {
System.out.println("Captured base: " + base);
}
};
r.run();
System.out.println("base is still: " + base);
Captured base: 10
base is still: 10
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27