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

Variable Capture: Effectively Final Requirement

Both lambdas and anonymous classes capture effectively final variables; migration maintains same rules.

Variable Capture: Effectively Final Requirement

What you'll learn: Both lambdas and anonymous classes must capture only effectively final variables from their surrounding scope—this rule stays identical when migrating between the two.

The Shared Constraint

When you learned about local classes and anonymous classes, you discovered the "effectively final" requirement: variables from the enclosing scope can only be accessed if they're never modified after initialization. This same rule applies to lambdas. Whether you write an anonymous class or convert it to a lambda, the captured variables must remain effectively final.

Why This Matters for Migration

When converting anonymous classes to lambdas (or vice versa), you don't need to worry about changing the variable capture rules. Both constructs follow identical restrictions:

public void processItems() {
    int threshold = 10;  // Effectively final
    int count = 0;       // NOT effectively final
    
    // Lambda captures threshold - OK
    Runnable r1 = () -> System.out.println("Threshold: " + threshold);
    
    count++;  // This modification makes count non-effectively final
    
    // Lambda cannot capture count - COMPILE ERROR
    // Runnable r2 = () -> System.out.println("Count: " + count);
    
    // Anonymous class has same restriction - COMPILE ERROR
    // Runnable r3 = new Runnable() {
    //     public void run() {
    //         System.out.println("Count: " + count);
    //     }
    // };
}

The Rule in Practice

A variable is effectively final if you could add the final keyword without changing the program's behavior. Both anonymous classes and lambdas capture variables by value, not by reference, which is why they freeze the variable's state at capture time.

Key Takeaway: The effectively final requirement is identical for lambdas and anonymous classes—captured variables must never be reassigned after initialization, making migration between the two styles seamless regarding variable capture.