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:
4 Comments
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(); } }Just type outerClassField.
I think the best way is:
class Outer {
class Inner {
void someMethod() {
return Outer.this.shadowedMethod();
}
}
Thanks man, that was exactly what I needed.