开发者

Implementing Clonable in Java

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 whic开发者_如何学运维h 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.


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.


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.

A clone = (A)super.clone();   // can't do this
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜