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

Accessing Local Variables from Local Classes

Understand how local classes can access effectively final local variables and parameters from enclosing scope.

Accessing Local Variables from Local Classes

What you'll learn: You'll learn the rules for when and how a local class can access variables declared in the method that contains it.

The Core Idea

A local class can access local variables and parameters from its enclosing method, but with one critical restriction: those variables must be effectively final. This means they can't be modified after they're initialized (though they don't need the final keyword explicitly written).

Think of it like this: imagine you write a note (the local class) while sitting at a desk (the method), and that note needs to reference items on the desk. Once you stand up and walk away (the method finishes executing), the note still exists somewhere else in memory. For the note to safely refer to those desk items, they must be items that never changed while you were writing—otherwise the note would have stale information.

Why This Restriction Exists

Methods execute and complete, their local variables disappearing from the stack. But objects—including instances of local classes—can outlive the method. Java ensures safety by capturing the values of local variables at the time the local class instance is created. If those variables could change, the local class would have an outdated copy, creating confusing bugs.

The Rules

  • Effectively final: A local variable is effectively final if it's never reassigned after initialization
  • Parameters count too: Method parameters follow the same rule
  • Reading is allowed: The local class can read these variables freely
  • Writing is forbidden: Any attempt to modify them breaks the effectively final contract

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