The
encounters a problem when trying to copy a composite object deeply. You must assume that the Clone () method in the member object can also duplicate its own handle in turn, and so on. This complicates our operations. In order for deep replication to work properly, you must control the code in all classes, or at least fully grasp the classes that are needed in deep replication to ensure that their own deep replication is done correctly.
The following example summarizes what needs to be done in the face of a composite object for deep replication:
: Deepcopy.java//Cloning a composed object class Depthreading implements cloneable {private double depth;
Public depthreading (double depth) {this.depth = depth;
public Object Clone () {object o = null;
try {o = Super.clone ();
catch (Clonenotsupportedexception e) {e.printstacktrace ();
return o;
} class Temperaturereading implements cloneable {private long time;
private double temperature;
Public temperaturereading (double temperature) {time = System.currenttimemillis ();
This.temperature = temperature;
public Object Clone () {object o = null;
try {o = Super.clone ();
catch (Clonenotsupportedexception e) {e.printstacktrace ();
return o;
} class Oceanreading implements cloneable {private depthreading depth;
private temperaturereading temperature;
Public oceanreading (double tdata, double ddata) {temperature = new temperaturereading (tdata); depth = NEW depthreading (Ddata);
Public Object Clone () {oceanreading o = null;
try {o = (oceanreading) super.clone ();
catch (Clonenotsupportedexception e) {e.printstacktrace ();
}//Must clone handles:o.depth = (depthreading) o.depth.clone ();
O.temperature = (temperaturereading) o.temperature.clone (); return o; Upcasts back to Object}} public class Deepcopy {public static void main (string[] args) {oceanreading Readi
ng = new Oceanreading (33.9, 100.5);
Now clone it:oceanreading r = (oceanreading) reading.clone (); }
} ///:~
Depthreading and temperaturereading are very similar; they all contain only basic data types. So the Clone () method can be very simple: call Super.clone () and return the result. Note that the Clone () code used by the two classes is exactly the same.
Oceanreading is a combination of depthreading and temperaturereading objects. In order to make a deep copy of it, Clone () must simultaneously clone the handle within the oceanreading. To achieve this goal, the results of the super.clone () must be shaped into a Oceanreading object (to access the depth and temperature handles).