I have read this concept in respect to static inner class : ViewHolder declared as inner class inside the adapter of ListView to enhance the performance of getView().
Consider the below class
public class OuterClass{
public class InnerClass{
private int privateProperty= -2;
}
public static void main(String[] args) {
OuterClass oc = new OuterClass();
InnerClass ic = oc.new InnerClass();
ic.privateProperty = -98;
}
}
If inner class contains private properties and an object of inner class is created inside a method of outer class then the inner class private properties can be accessed directly using . 'dot' operator.
I have read somewhere that the private properties of the inner class are accessed using synthetic setter getter methods from outer class
I want to clear my concept regarding the same.
解决方案
The compiler generates method to access private members of an inner class. If you compile your example code and examine the bytecode, you will find that it is as if it were written like this:
public class OuterClass{
public class InnerClass{
private int privateProperty= -2;
static int access$002(InnerClass obj, int value) {
obj.privateProperty = value;
return value;
}
}
public static void main(String[] args) {
OuterClass oc = new OuterClass();
InnerClass ic = oc.new InnerClass();
InnerClass.access$002(ic, -98);
}
}
This conversion of the line
ic.privateProperty = -98;
into the method call:
InnerClass.access$002(ic, -98);
together with the creation of the static method InnerClass.access$002 is done by the compiler. The static method (named access$002 by my compiler) is an example of a "synthetic setter method" you have read about. As a result, the bytecode for the two classes do not violate Java's access rules.