在 Java 中实现 Clonable
在哪些情况下应该使用这种方式:
public A clone() throws CloneNotSupportedException {
A clone = (A)super.clone();
clone.x= this.x;
return clone;
}
在哪些情况下应该使用那种方式:
public ShiftedStack clone() throws CloneNotSupportedException {
return new A(this.x);
}
如果 x
是最终的并且我想使用第一种方式,我该怎么办?
对于第一种方式,我是这样理解的:我们克隆超类并向上转换它,导致一些成员未初始化。之后初始化这些成员。我的理解正确吗?
谢谢。
In which cases should I use this way:
public A clone() throws CloneNotSupportedException {
A clone = (A)super.clone();
clone.x= this.x;
return clone;
}
And in which cases should I use that way:
public ShiftedStack clone() throws CloneNotSupportedException {
return new A(this.x);
}
What should I do if x
is final and I want to use the first way?
Regarding the first way, I understand it like this: we clone the super class and up-cast it, leading to some members uninitialized. After this initialize these members. Is my understanding correct?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一种方法行不通。您无法向上转换父类的克隆。它将是父类的一个实例。
the first method won't work. You can't upcast the clone of the parent class. It would be an instance of the parent class.
有两件事:
1)在第一种形式中,不需要浅复制数据成员(clone.x=this.x)。 Object.clone() 会为你做这件事。
2)使用第二种形式时要小心:它总是创建一个具体类型A的实例,因此如果你用B扩展A,那么B.clone()将无法再使用其超类的clone方法。
--编辑--
关于你的问题,如果方法clone()在类X的层次结构中正确实现,那么在类X的实现中调用super.clone()将返回类型X。从 Object 继承的默认 clone() 是一个“魔术方法”,从某种意义上说,它创建了调用它的具体类的实例。它还执行所有数据成员的浅表复制。通常,在clone()的实现中,您会执行一些深度复制,以避免源和克隆之间共享可变对象的引用。
Two things:
1) In the first form, there is no need to shallow copy data members (clone.x=this.x). Object.clone() does it for you.
2) Be careful when using the second form: it always creates an instance of concrete type A, therefore if you extend A with B, then B.clone() will not be able to use its superclass' clone method anymore.
--EDIT--
Regarding your question, if the method clone() is implemented properly up the hierarchy of class X, then calling super.clone() in the implementation of class X will return an instance of type X. The default clone() inherited from Object is a "magic method", in the sense that it creates an instance of the concrete class it is called from. It also performs a shallow copy of all data members. Usually, in the implementation of clone() you perform some deep copying, in order to avoid shared references of mutable objects between the source and the clone.