Core Java: An anonymous class captures effectively final locals but cannot reassign them

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.

Code
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);
Output
Captured base: 10
base is still: 10
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms