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; } }); } }