Scope and Shadowing in Local Classes
What you'll learn: How name conflicts are resolved when a local class declares fields with the same name as variables in the enclosing scope.
The Core Problem
When you declare a local class inside a method, you have access to three different "layers" of variables:
- The local class's own fields
- The enclosing method's local variables
- The enclosing class's fields
Shadowing occurs when a variable in an inner scope has the same name as a variable in an outer scope. The inner variable "hides" or "shadows" the outer one.
How Shadowing Works in Local Classes
If a local class declares a field with the same name as:
- A local variable in the enclosing method → the local class's field shadows it
- A field in the enclosing class → the local class's field shadows it too
To access the shadowed variables, you need to be explicit:
- Use
this.variableNameto refer to the local class's field - Use
EnclosingClass.this.variableNameto refer to the enclosing class's field - You cannot access a shadowed local variable — once shadowed by the local class's field, the method's local variable becomes inaccessible within that local class
A Mental Model
Think of it like nested rooms. If each room has a lamp named "light," when you say "turn on the light" while standing in the innermost room, you're referring to that room's lamp. To control a lamp in an outer room, you need to specify which room you mean.
Why This Matters
Shadowing can create confusion and bugs. Most style guides recommend avoiding shadowing entirely by using distinct names. However, understanding the rules helps you recognize and fix these issues when they arise in existing code.
Key Takeaway: In local classes, fields shadow identically-named local variables and enclosing class fields; use this or OuterClass.this qualifiers to disambiguate, but shadowed local variables become completely inaccessible.