I have the following code. I want to get hold of the outer class object using which I created the inner class object inner
. How can I do it?
pub
The more general answer to this question involves shadowed variables and how they are accessed.
In the following example (from Oracle), the variable x in main() is shadowing Test.x:
class Test {
static int x = 1;
public static void main(String[] args) {
InnerClass innerClassInstance = new InnerClass()
{
public void printX()
{
System.out.print("x=" + x);
System.out.println(", Test.this.x=" + Test.this.x);
}
}
innerClassInstance.printX();
}
public abstract static class InnerClass
{
int x = 0;
public InnerClass() { }
public abstract void printX();
}
}
Running this program will print:
x=0, Test.this.x=1
More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6
Here's the example:
// Test
public void foo() {
C c = new C();
A s;
s = ((A.B)c).get();
System.out.println(s.getR());
}
// classes
class C {}
class A {
public class B extends C{
A get() {return A.this;}
}
public String getR() {
return "This is string";
}
}