实现clone()方法,里面new一个实例并初始化必要的变量。

解决方案 »

  1.   

    可以看看think in java的相关章节
      

  2.   

    clone() method
    The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation. 
      

  3.   

    /*
     * @(#)HowCanClone.java     2002/02/25
     * Copyright 2002 bluesea.com, Inc. All Rights Reserved.
     *//*
     * clone 在 Object 类中是个 protected 的方法
     * 要使一个类有clone能力,必须做下面3件事情:
     * (1) override method clone,使它变成 public
     * (2) 在clone方法中调用 super.clone();
     * (3) implements Cloneable 接口
     */class MyInteger implements Cloneable {
    private int i;

    public MyInteger(int i) {
    this.i = i;
    }

    public Object clone() throws CloneNotSupportedException {
    Object o;
    o = super.clone();
    return o;
    }

    public void increment() {
    i++;
    }

    public String toString() {
    return Integer.toString(i);
    }
    }/**
     * Class <code>HowCanClone</code>
     * @author [email protected]
     * @version 1.0
     */
    public class HowCanClone {
    public static void main(String[] args) throws CloneNotSupportedException {
    MyInteger a = new MyInteger(10);
    MyInteger b = (MyInteger)a.clone();

    System.out.println("a = " + a);
    System.out.println("b = " + b);

    System.out.println("b.increment");
    b.increment(); System.out.println("a = " + a);
    System.out.println("b = "+ b); }
    }注意:
        clone只实现了浅层clone。