Shadowing and Name Resolution in Inner Classes
What you'll learn: How Java resolves variable names when inner and outer classes both declare fields with the same name.
When an inner class and its outer class both have a field with the same name, the inner class field shadows (hides) the outer class field. This is similar to how a local variable can shadow a field—the closest scope wins.
The Shadowing Problem
If your inner class declares a field named value and the outer class also has a field named value, any unqualified reference to value inside the inner class refers to the inner class's field. The outer field is hidden but not gone—you just need a qualified reference to access it.
Name Resolution Rules
Java searches for variables in this order:
- Local variables and parameters (closest scope)
- Inner class fields
- Outer class fields (using
OuterClass.this.fieldName)
Syntax for Accessing Shadowed Fields
class Outer {
private int value = 10;
class Inner {
private int value = 20; // Shadows outer 'value'
void display() {
int value = 30; // Local variable, shadows both
System.out.println(value); // 30 (local)
System.out.println(this.value); // 20 (inner field)
System.out.println(Outer.this.value); // 10 (outer field)
}
}
}
The key is using Outer.this.value to explicitly refer to the outer class's field when it's shadowed.
When This Matters
Shadowing is usually unintentional and can cause confusion. It's best to use distinct field names. However, understanding resolution rules is crucial for debugging and reading code where shadowing does occur.
Key Takeaway: When an inner class field has the same name as an outer class field, the inner field shadows the outer one; use OuterClassName.this.fieldName to access the shadowed outer field explicitly.