集册 Java实例教程 支持浅克隆的类

支持浅克隆的类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

520
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
支持浅克隆的类

public class Main {

  public static void main(String[] args) {
  /*
  时代Java公众号 - N o w J a  v a . c o m 提 供
  */

    ShallowClone sc = new ShallowClone(100.00);

    ShallowClone scClone = (ShallowClone) sc.clone();


    // Print the value in original and clone

    System.out.println("Original:" + sc.getValue());

    System.out.println("Clone :" + scClone.getValue());


    // Change the value in original and it will change the value

    // for clone too because we have done shallow cloning

    sc.setValue(200.00);


    // Print the value in original and clone

    System.out.println("Original:" + sc.getValue());

    System.out.println("Clone :" + scClone.getValue());

  }

}


class MyClass implements Cloneable {/*来 自 NowJava.com - 时代Java*/

  private double value;


  public MyClass(double value) {

    this.value = value;

  }


  public void setValue(double value) {

    this.value = value;

  }


  public double getValue() {

    return this.value;

  }


  public Object clone() {

    MyClass copy = null;

    try {

      // Call the clone() method of the Object class

      copy = (MyClass) super.clone();

    } catch (CloneNotSupportedException e) {

      // If anything goes wrong during cloning, print the error details

      e.printStackTrace();

    }

    return copy;

  }

}


class ShallowClone implements Cloneable {

  private MyClass holder = new MyClass(0.0);


  public ShallowClone(double value) {

    this.holder.setValue(value);

  }


  public void setValue(double value) {

    this.holder.setValue(value);

  }


  
展开阅读全文