Course contentsShow
← Java
Lesson 644 of 2,87015. Nested and Inner ClassesFree lesson

Accessing Enclosing Scope Variables

Understand how anonymous classes capture effectively final variables from the enclosing scope.

Accessing Enclosing Scope Variables

What you'll learn: You'll understand how anonymous classes can capture and use variables from the surrounding method or block, but only when those variables are effectively final.


The Core Idea

When you create an anonymous class inside a method, that class can "see" and use variables from the enclosing method's scope. However, Java has a strict rule: you can only access variables that are effectively final—meaning they're never reassigned after initialization.

Think of it like this: the anonymous class is taking a "snapshot" of the variable's value. Since the anonymous object might live longer than the method that created it (stored and called later), Java needs to ensure the captured value won't change unexpectedly. By requiring effective finality, Java guarantees the captured value remains stable.

How It Works

public class Demo {
    public void createRunner() {
        int count = 5;           // effectively final
        String message = "Run";  // effectively final
        
        Runnable runner = new Runnable() {
            @Override
            public void run() {
                // Can access both variables
                System.out.println(message + " " + count + " times");
            }
        };
        
        runner.run();  // Output: Run 5 times
        
        // count = 10;  // ERROR if uncommented: makes count NOT effectively final
    }
}

The anonymous Runnable class "captures" both count and message from the enclosing scope. As long as neither variable is reassigned, this works perfectly.

Why the Restriction Matters

If you could modify captured variables, you'd create confusing situations where the anonymous object's behavior changes unpredictably based on when it executes relative to modifications in the enclosing method.

Key Takeaway: Anonymous classes can access local variables and parameters from their enclosing scope, but only if those variables are effectively final (never reassigned after initialization).