I have written below code that is working fine but i have one doubt about synthetic method. As these are generated to access private data. but i am having public instance variable of outer class that is used in member class, so for accessing instance variable it has created synthetic method (As it is in class file!!).
code snippet is as :
public class TestInnerClass {
public int x = 10;
public static void main(String[] args) {
TestInnerClass test= new TestInnerClass();
A obj = test.new A();
obj.display();
}
class A {
void display() {
System.out.println(x);
}
}
}
class file is generated as below. For inner class A as TestInnerClass$A:
import java.io.PrintStream;
class TestInnerClass$A {
TestInnerClass$A(TestInnerClass paramTestInnerClass) {
}
void display() {
System.out.println(this.this$0.x);
}
}
class file is generated for TestInnerClass :
import java.io.PrintStream;
public class TestInnerClass {
public int x = 10;
public static void main(String[] args) {
TestInnerClass test = new TestInnerClass();
TestInnerClass tmp13_12 = test; tmp13_12.getClass(); A obj = new A();
obj.display();
}
class A {
A() {
}
void display() {
System.out.println(TestInnerClass.this.x);
}
}
}
So my doubt are:
1). why the display method is having different different definition in class files??
2). why in TestInnerClass class file instance variable is accessed as TestInnerClass.this.x. but the same code is different in class file of TestInnerClass$A as this.this$0.x??
3) why JVM created synthetic method as this$0, however instance variable is public??