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

Effectively Final Requirement

Learn why local variables accessed by local classes must be effectively final and what that means.

Effectively Final Requirement

You'll learn why local variables accessed by local classes must be effectively final and what that restriction means.

What Does "Effectively Final" Mean?

When a local class accesses a local variable from its enclosing method, Java requires that variable to be effectively final. This means:

  • The variable is never assigned to after its initialization
  • It doesn't need the final keyword, but it behaves as if it had it

If you try to reassign a local variable after a local class references it, your code won't compile.

Why This Restriction Exists

Local variables live on the method's stack and disappear when the method completes. But objects of the local class can outlive the method. To make this work safely, Java captures a copy of the local variable's value when creating the local class instance.

If the variable could change after being captured, you'd have two different values: the original in the method and the copy in the local class. This would create confusing bugs where changes don't appear where expected.

Analogy: Imagine photocopying a document. If someone edits the original after you make the copy, your copy doesn't magically update. Java avoids this confusion by only allowing you to "photocopy" variables that won't change.

Example Context

void processNames() {
    String prefix = "Mr. ";  // effectively final - never reassigned
    
    class NameFormatter {
        String format(String name) {
            return prefix + name;  // OK - prefix is effectively final
        }
    }
    
    // prefix = "Dr. ";  // If uncommented, compilation error!
    
    NameFormatter formatter = new NameFormatter();
}

Key Takeaway: Local variables accessed by local classes must be effectively final (never reassigned) because the local class captures their values, and allowing changes would create inconsistent state between the method and the class instance.