Quote:Original post by Fred304
Quote:Original post by CaptainJester
You call super.clone() to make it a deep copy. But you also have to copy your own data.
I did a little more research - and these statements are definately wrong!
Quote:http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#clone()
If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified.
The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
what this means is that a clone of this class;
class Something implements Cloneable{public int primitiveI;public Integer classI;//implement the clone interface}
will create two classes, each with a copy of primitiveI with equivalent, and each with a copy of classI with equivalent values. It is at this point important to note that object references are more analogous to C++ pointers. classI is storing a memory address. So, that memory address is being copied and stored in the clone's classI member, but it points to the
same instance of the Integer class that the original instance's classI member points to.
so, using the code from above
Something a = new Something();a.primitiveInt = 3;a.classInt = new Integer(7);Something b = a.clone();a.primitiveInt = 4;a.classInt.setValue(10); //if we could do such a thing, as opposed to creating a new Integer instance
a.primitiveInt is now 4, b.primitiveInt is still 3.
a.classInt and b.classInt are both 10.