如何将Java中的克隆合成基础对象类

    作者:课课家教育更新于: 2016-02-21 16:18:50

    大神带你学编程,欢迎选课

      试图深层复制合成对象时会遇到一个问题。必须假定成员对象中的clone()方法也能依次对自己的句柄进行深层复制,以此类推。这使我们的操作变得复杂。为了能正常实现深层复制,必须对所有类中的代码进行控制,或者至少全面掌握深层复制中需要涉及的类,确保它们自己的深层复制能正确进行。

    如何将Java中的克隆合成基础对象类_Java基础类_Java的克隆_课课家

      下面这个例子总结了面对一个合成对象进行深层复制时需要做哪些事情:

      //: 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 reading =

      new OceanReading(33.9, 100.5);

      // Now clone it:

      OceanReading r =

      (OceanReading)reading.clone();

      }

      } ///:~

      DepthReading和TemperatureReading非常相似;它们都只包含了基本数据类型。所以clone()方法能够非常简单:调用super.clone()并返回结果即可。注意两个类使用的clone()代码是完全一致的。

      OceanReading是由DepthReading和TemperatureReading对象合并而成的。为了对其进行深层复制,clone()必须同时克隆OceanReading内的句柄。为达到这个目标,super.clone()的结果必须造型成一个OceanReading对象(以便访问depth和temperature句柄)。

课课家教育

未登录

1