Java private field access possible when having a reference?

前端 未结 7 1347
野性不改
野性不改 2020-12-19 03:12

I came across the following \"strange\" feature today - if you have a reference to an object from the class A in the body of the class A you can access the private fields of

相关标签:
7条回答
  • 2020-12-19 03:51

    It is intended to be this way.

    Citing the Java Language Specification:

    A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:

    • ...
    • (Otherwise,) if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member.
    • ...
    0 讨论(0)
提交回复
热议问题