clonedemo2.java~2~

来自「java2参考大全上的例子的源码和自己的理解.」· JAVA~2~ 代码 · 共 44 行

JAVA~2~
44
字号
package clone;

/**
 下面的例子重载clone( )方法以便它能被其类外的程序所调用。为了完成这项功能,它
 的存取说明符必须是public,如下所示:

 */

// Override the clone() method.

class TestClone
    implements Cloneable {
  int a;
  double b;

  // clone() is now overridden and is public.
  public Object clone() {
    try {
      // call clone in Object.
      return super.clone();
    }
    catch (CloneNotSupportedException e) {
      System.out.println("Cloning not allowed.");
      return this;
    }
  }
}

class CloneDemo2 {
  public static void main(String args[]) {
    TestClone x1 = new TestClone();
    TestClone x2;

    x1.a = 10;
    x1.b = 20.98;

    // here, clone() is called directly.
    x2 = (TestClone) x1.clone();

    System.out.println("x1: " + x1.a + " " + x1.b);
    System.out.println("x2: " + x2.a + " " + x2.b);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?