views:

124

answers:

2

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.

+4  A: 

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.

Eyal Schneider
A: 

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
objects
@objects: Try it... :)
Eyal Schneider
This is not true. From the documentation for `Object#clone()`, `By convention, the returned object should be obtained by calling super.clone. If a class and all of its superclasses (except Object) obey this convention, it will be the case that x.clone().getClass() == x.getClass().`
Matthew T. Staebler