Cloning implementation in Java

When should I use this way:

public A clone() throws CloneNotSupportedException {
    A clone = (A)super.clone();
    clone.x= this.x;
    return clone;
}

      

And in what cases should I use this way:

public ShiftedStack clone() throws CloneNotSupportedException {
    return new A(this.x);
}

      

What if it x

is final and I want to use the first method?

As for the first way, I understand it this way: we clone the superclass and raise it, leading to the fact that some members are uninitialized. Then, initialize these members. Do I understand correctly?

Thanks.

+2


a source to share


2 answers


Two things:

1) In the first kind, there is no need for shallow copy data items (clone.x = this.x). Object.clone () does this for you.

2) Be careful when using the second form: it always instantiates a specific type A, so if you extend A with B then B.clone () will no longer be able to use its superclass clone method.



- EDIT -

As for your question, if the clone () method is correctly injected into the hierarchy of class X, then calling super.clone () in the implementation of class X will return an instance of type X. By default, clone () inherited from Object is a "magic method", in in the sense that it instantiates the class of the concrete class from which it is called. It also performs a shallow copy of all data members. Typically in your clone () implementation, you do deep copying to avoid shared mutable references between the source and the clone.

+4


a source


the first method won't work. You cannot rescan a clone of the parent class. This will be an instance of the parent class.



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

      

-2


a source







All Articles