Why do inner classes make private methods accessible?

前端 未结 4 797
难免孤独
难免孤独 2020-11-28 06:25

I don\'t understand why this compiles. f() and g() are visible from the inner classes, despite being private. Are they treated special specially because they are inner clas

4条回答
  •  春和景丽
    2020-11-28 07:31

    Java compiles in special accessors with $ in them. So you can't write Java that access the private methods. Explained here:

    http://www.retrologic.com/innerclasses.doc7.html

    There is one more category of compiler-generated members. A private member m of a class C may be used by another class D, if one class encloses the other, or if they are enclosed by a common class. Since the virtual machine does not know about this sort of grouping, the compiler creates a local protocol of access methods in C to allow D to read, write, or call the member m. These methods have names of the form access$0, access$1, etc. They are never public. Access methods are unique in that they may be added to enclosing classes, not just inner classes.

提交回复
热议问题