Why can clone set a private field on another object?

梦想与她 提交于 2019-11-30 18:11:04

问题


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 though buffer is private. It seems like it should require the field to be protected for this to work.

Why is this allowed? Does clone() have special privileges that allows it to access the private fields?

public class IntegerStack implements Cloneable {
    private int[] buffer;
    private int top;

    // ... code omitted ...

    @Override
    public IntegerStack clone() {
        try{
            IntegerStack nObj = (IntegerStack) super.clone();
            nObj.buffer = buffer.clone();
            return nObj;
        } catch (CloneNotSupportedException e)
        {
            throw new InternalError(e.toString());
        }
    }
}

回答1:


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?)



来源:https://stackoverflow.com/questions/976243/why-can-clone-set-a-private-field-on-another-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!