posts - 495,  comments - 11,  trackbacks - 0

How to clone:

1. Implement the Cloneable interface, and

2. Redefine the clone method with the public access modifier.


Cloneable:

The Cloneable interface is one of a handful of tagging interfaces that Java provides.A tagging interface has no methods; its only purpose is to allow the use of instanceof in a type inquiry:
if (obj instanceof Cloneable) . . .
We recommend that you do not use this technique in your own programs.


Shallow copy:

Even if the default (shallow copy) implementation of clone is adequate, you still need to implement the Cloneable interface, redefine clone to be public, and call super.clone(). Here is an example:

class Employee implements Cloneable
{
   // raise visibility level to public, change return type
   public Employee clone() throws CloneNotSupportedException
   {
      return super.clone();
   }
   . . .
}


Deep copy:

class Employee implements Cloneable
{
   . . .
   public Object clone() throws CloneNotSupportedException
   {
      // call Object.clone()
      Employee cloned = (Employee) super.clone();

      // clone mutable fields
      cloned.hireDay = (Date) hireDay.clone()

      return cloned;
   }
}

1 The clone method of the Object class threatens to throw a CloneNotSupportedException—it does that whenever clone is invoked on an object whose class does not implement the Cloneable interface. Of course, the Employee and Date class implements the Cloneable interface, so the exception won't be thrown.

2
public Employee clone()
{
   try
   {
      return super.clone();
   }
   catch (CloneNotSupportedException e) { return null; }
   // this won't happen, since we are Cloneable
}

This is appropriate for final classes. Otherwise, it is a good idea to leave the tHRows specifier in place. That gives subclasses the option of throwing a CloneNotSupportedException if they can't support cloning.


Use clone:

public static void main(String[] args) {
     try {
        Employee original = new Employee("John Q. Public", 50000);
        original.setHireDay(2000, 1, 1);
        Employee copy = original.clone();
        copy.raiseSalary(10);
        copy.setHireDay(2002, 12, 31);
        System.out.println("original=" + original);
        System.out.println("copy=" + copy);
    }
    catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
}

posted on 2007-11-10 10:39 jadmin 阅读(73) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: