集册 Java实例教程 具有克隆能力的类

具有克隆能力的类

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

613
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
具有克隆能力的类
/*
时代Java 提 供
*/

public class Main {

  public static void main(String[] args) {

    MyClass dh = new MyClass(100.00);

    // Clone dh

    MyClass dhClone = (MyClass) dh.clone();


    // Print the values in original and clone

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

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


    // Change the value in original and clone

    dh.setValue(2.00);

    dhClone.setValue(4.00);


    // Print the values in original and clone again

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

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

  }

}
/**来自 
 nowjava**/


class MyClass implements Cloneable {

  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 {

      
展开阅读全文