Java Nested Inner Class This

Here is a Java certification sort of question. Inside a nested inner class, how do you refer to the containing outer class?

public class MyClass {
  private String outerClassField = "some value";

  public void outerClassMethod() {
    someObject.addMyListener(new MyListener() {
      public void processEvent(MyEvent e) {
        // How do you access the variable outerClassField?
      }
    });
  }
}

You can’t use the this keyword because that will reference the inner class! The only way I know about, and that I have used before, is to use the class name. Such as the following example.

public class MyClass {
  private String outerClassField = "some value";

  public void outerClassMethod() {
    someObject.addMyListener(new MyListener() {
      public void processEvent(MyEvent e) {
        MyClass.this.outherClassField;
      }
    });
  }
}

Related posts:

  1. Java.class
  2. Jakarta BeanUtils PropertyUtils Nested Properties
  3. Gnarly Custom Groovy Closures
  4. Java Five-Oh #3: Variable Arguments
  5. Jakarta BeanUtils PropertyUtils
  6. Class HighLite Collections


5 Responses to “Java Nested Inner Class This”

  • Paul Says:

    Well… if you didn’t know about that, there is at least one other way:

    class Outer {
      final outer = this;
    
      class Inner {
        void someMethod() {
          return outer.shadowedMethod();
       }
    }
    
  • Robert Says:

    Just type outerClassField.

  • Lyden Says:

    I think the best way is:

    class Outer {
    class Inner {
    void someMethod() {
    return Outer.this.shadowedMethod();
    }
    }

  • Pat Says:

    Thanks man, that was exactly what I needed.

  • diabol Says:

    @Paul
    Chicken and Egg.
    Not exactly obvious, but to access “shadowedMethod” in your example you first have to access “outer” which is declared in the outer scope, so you implicitly access outer.

    class Outer {
      final outer = this;
      class Inner {
        final outer = this;
        private foo() { outer.shadowedMethod(); }
      }
    }
    

    Fails for this example, you’d need Outer.this.outer.shadowedMethod to explicitly distinguish them both, which kinda defeats the purpose.

Leave a Reply