Cloneable interface is an empty interface, only for tagging objects, the Cloneable interface is not the Clone () method, the Clone () method is the method inside the object class! The default implementation is a native method
Protected native Object clone () throws Clonenotsupportedexception;
Overwrite the Clone method if the object implement the Cloneable interface (because the Clone method of the object class is protected and needs to be overwritten as public)
Public Object Clone () throws Clonenotsupportedexception{return Super.clone ();}
the Clone () method in the object class is used only for shallow copies (copy basic member properties, only return a reference to a changed address for a reference type)
Deep copy requires a re-overwrite of the Clone method.
public class Testdeepclone implements cloneable {public int num = 0;public String str = "Default";p ublic A a;public Object Clone () throws Clonenotsupportedexception {testdeepclone o = (testdeepclone) super.clone (); o.str = new String (THIS.STR); O.A = (a) a.clone (); return o;}} The member attribute a must be cloneable, otherwise it cannot clone its combined class A implements Cloneable {public Object clone () throws clonenotsupportedexception {return super.clone ();}}
use serialization to achieve deep replication
The process of writing an object to a stream is a serialization (serilization) process, and reading the object from the stream is a parallelization (deserialization) process. It should be noted that a copy of the object is written in the stream, and the original object still exists inside the JVM.
In the Java language, a deep copy of an object can often be accomplished by implementing an serializable interface and then writing the object (actually a copy of the object) into a stream and then reading it from the stream to reconstruct the object.
This is done only if the object and all objects referenced inside the object are serializable, otherwise it is necessary to carefully examine whether the non-serializable objects are set to transient, thereby excluding them from the replication process. The code improvements are as follows:
Java Clone () deep copy, shallow copy