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. Ruby Class Tutorial
  4. Class HighLite Collections
  5. Gnarly Custom Groovy Closures

This entry was posted in TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Paul
    Posted April 16, 2010 at 4:33 pm | Permalink

    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();
       }
    }
    
  2. Robert
    Posted August 2, 2010 at 7:43 pm | Permalink

    Just type outerClassField.

  3. Lyden
    Posted August 10, 2010 at 8:38 am | Permalink

    I think the best way is:

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

  4. Pat
    Posted September 11, 2011 at 4:44 pm | Permalink

    Thanks man, that was exactly what I needed.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*