为什么clone可以在另一个对象上设置私有字段? [英] Why can clone set a private field on another object?

查看:138
本文介绍了为什么clone可以在另一个对象上设置私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,而我正在阅读的书中有关于克隆的以下示例。在 clone()中,我的第一个实例能够在新对象上设置缓冲区,即使缓冲区是 private 。似乎它应该要求字段 protected 才能使用。

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.

为什么允许这样做? clone()是否具有允许其访问私有字段的特殊权限?

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());
        }
    }
}


推荐答案

private 修饰符并不意味着只有同一个实例才能访问该字段;这意味着只有同一个类的对象才能访问它。

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.

Java语言规范§中说6.6,访问控制


...如果成员或构造函数被声明为私有,则仅允许访问如果它出现在顶级类的主体内( §7.6)包含成员或构造函数的声明。

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

换句话说,类中的任何内容都可以访问它在任何时候。即使是嵌套类也可以访问封闭类中的 private 成员和构造函数,反之亦然。

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

这篇关于为什么clone可以在另一个对象上设置私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆