Why can clone set a private field on another object?

后端 未结 1 630
北海茫月
北海茫月 2021-01-06 17:25

I\'m learning Java, and the book I\'m reading has the following example on cloning. In clone(), my first instance is able to set buffer on the new object even t

相关标签:
1条回答
  • 2021-01-06 17:55

    The private modifier does not mean that only the same instance can access the field; it means only objects of the same class can access it.

    The Java Language Specification says in §6.6, Access Control:

    ... 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 or constructor.

    In other words, anything inside the class can access it at any time. Even nested classes can access private members and constructors in the enclosing class, and vice versa.

    (You're not alone in misunderstanding it; check out this much-upvoted answer to "What is your longest-held programming assumption that turned out to be incorrect?)

    0 讨论(0)
提交回复
热议问题