Qualifying this: OuterClass.this
You'll learn how to explicitly refer to the outer class instance when the inner class's this reference isn't enough.
The Name Collision Problem
When you're inside an inner class, the keyword this refers to the inner class instance, not the outer one. But what if the inner class and outer class both have fields or methods with the same name? Or what if you need to pass the outer instance to a method?
Java provides a special syntax: OuterClass.this—which explicitly refers to the enclosing outer class instance.
How It Works
Think of it like a fully-qualified address. Just as you'd say "John's house" versus "Mary's house" to distinguish between two houses, you use OuterClass.this to say "I mean the outer instance's this, not the inner one."
Syntax:
OuterClassName.this
When You Need It
You'll use this syntax when:
- The inner and outer classes have fields/methods with identical names
- You need to return or pass the outer instance reference
- You want to call an outer class method that's shadowed by an inner class method
Example:
class Building {
private String address = "123 Main St";
class Apartment {
private String address = "Apt 5B";
void printAddresses() {
System.out.println(address); // "Apt 5B" (inner)
System.out.println(this.address); // "Apt 5B" (inner)
System.out.println(Building.this.address); // "123 Main St" (outer)
}
}
}
Key Takeaway: Use OuterClass.this to explicitly access the outer instance when this alone would refer to the inner class, resolving name conflicts and accessing outer members unambiguously.