All 15 Inner Classes & Anonymous Classes questions
More in Inner Classes & Anonymous Classes
Advertisement
Back to results for “OOP”
Java › Inner Classes & Anonymous Classes

How would you access the enclosing outer class's instance from within a nested inner class when there's a naming conflict (like a shadowed field with the same name), using the OuterClassName.this syntax?

Intermediate

Answer

When an inner class has its own field or local variable with the same name as one in the enclosing outer class (shadowing it, making the inner class's own version the one referenced by a plain, unqualified name), the qualified syntax OuterClassName.this.fieldName explicitly disambiguates and refers specifically to the outer instance's version of that member, bypassing the inner class's own shadowing member entirely -- this qualified `this` reference is also generally useful anytime you need an explicit reference to the enclosing instance itself (not just for disambiguating a naming conflict), such as passing the outer instance as an argument to another method.
public class Outer {
    private String name = "outer";

    class Inner {
        private String name = "inner";  // shadows Outer's 'name' field

        void printNames() {
            System.out.println(name);            // "inner" -- refers to Inner's own field
            System.out.println(this.name);       // "inner" -- same, explicit but still Inner's own
            System.out.println(Outer.this.name);  // "outer" -- explicitly qualified, refers to the OUTER instance's field
        }
    }
}
Real-world example A nested class intentionally shadowing an outer class's field name (perhaps unavoidably, due to independently evolving code) uses the Outer.this.fieldName qualified syntax specifically where it needs to unambiguously reference the outer instance's version, avoiding a subtle bug where an unqualified reference would silently resolve to the inner class's own shadowing field instead.

Common follow-ups: Is this same qualified-this syntax needed (or even valid) for a STATIC nested class, given it has no outer instance at all?;How would you access an outer-outer instance from a doubly-nested inner class (an inner class within an inner class)?