Source of DeepCopy.java


  1: //: appendixa:DeepCopy.java
  2: // From 'Thinking in Java, 2nd ed.' by Bruce Eckel
  3: // www.BruceEckel.com. See copyright notice in CopyRight.txt.
  4: // Cloning a composed object.

  6: class DepthReading implements Cloneable {
  7:   private double depth;
  8:   public DepthReading(double depth) { 
  9:     this.depth = depth;
 10:   }
 11:   public Object clone() {
 12:     Object o = null;
 13:     try {
 14:       o = super.clone();
 15:     } catch(CloneNotSupportedException e) {
 16:       e.printStackTrace(System.err);
 17:     }
 18:     return o;
 19:   }
 20: }

 22: class TemperatureReading implements Cloneable {
 23:   private long time;
 24:   private double temperature;
 25:   public TemperatureReading(double temperature) {
 26:     time = System.currentTimeMillis();
 27:     this.temperature = temperature;
 28:   }
 29:   public Object clone() {
 30:     Object o = null;
 31:     try {
 32:       o = super.clone();
 33:     } catch(CloneNotSupportedException e) {
 34:       e.printStackTrace(System.err);
 35:     }
 36:     return o;
 37:   }
 38: }

 40: class OceanReading implements Cloneable {
 41:   private DepthReading depth;
 42:   private TemperatureReading temperature;
 43:   public OceanReading(double tdata, double ddata){
 44:     temperature = new TemperatureReading(tdata);
 45:     depth = new DepthReading(ddata);
 46:   }
 47:   public Object clone() {
 48:     OceanReading o = null;
 49:     try {
 50:       o = (OceanReading)super.clone();
 51:     } catch(CloneNotSupportedException e) {
 52:       e.printStackTrace(System.err);
 53:     }
 54:     // Must clone references:
 55:     o.depth = (DepthReading)o.depth.clone();
 56:     o.temperature = 
 57:       (TemperatureReading)o.temperature.clone();
 58:     return o; // Upcasts back to Object
 59:   }
 60: }

 62: public class DeepCopy {
 63:   public static void main(String[] args) {
 64:     OceanReading reading = 
 65:       new OceanReading(33.9, 100.5);
 66:     // Now clone it:
 67:     OceanReading r = 
 68:       (OceanReading)reading.clone();
 69:   }
 70: } ///:~