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:
April 16th, 2010 at 4:33 pm
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(); } }August 2nd, 2010 at 7:43 pm
Just type outerClassField.
August 10th, 2010 at 8:38 am
I think the best way is:
class Outer {
class Inner {
void someMethod() {
return Outer.this.shadowedMethod();
}
}
September 11th, 2011 at 4:44 pm
Thanks man, that was exactly what I needed.
July 1st, 2012 at 4:56 pm
@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.