为什么克隆可以在另一个对象上设置私有字段?
我正在学习Java,我正在阅读的书有以下关于克隆的示例。 在clone()中,我的第一个实例能够在新对象上设置缓冲区,即使缓冲区是私有的。 似乎应该要求该字段受到保护
才能正常工作。
为什么这是允许的? clone()
是否具有允许其访问 private
字段的特殊权限?
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());
}
}
}
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());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
private
修饰符并不意味着只有同一个实例才能访问该字段; 这意味着只有同一类的对象才能访问它。Java 语言规范在§6.6,访问控制:
换句话说,类内的任何内容都可以随时访问它。 即使嵌套类也可以访问封闭类中的私有成员和构造函数,反之亦然。
(您并不是唯一一个误解它的人;请查看 这个备受好评的答案“你最长持有的编程假设被证明是不正确的?)
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:
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?)