clone 创建对象副本 - webdancer's Blog

clone 创建对象副本

webdancer posted @ 2010年3月21日 09:27 in 编程语言 , 1242 阅读
public interface Cloneable

 此类实现了 Cloneable 接口,以指示方法Object.clone()可以合法地对该类实例进行按字段复制。

如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法,则会导致抛出 CloneNotSupportedException 异常。

按照惯例,实现此接口的类应该使用公共方法重写 Object.clone(它是受保护的)。请参阅 Object.clone(), 以获得有关重写此方法的详细信息。

但是如果直接查询JDK文档会发现Cloneable接口中并没有任何的方法定义,所以此接口在设计上称为是一种标识接口,表示对象可以被克隆。

 

  1. class Person implements Cloneable { // 
    必须实现Cloneable接口
     
  2.     private String name = null;  
  3.     public Person(String name) {  
  4.         this.name = name;  
  5.     }  
  6.     public void setName(String name) {  
  7.         this.name = name;  
  8.     }  
  9.     public String getName() {  
  10.         return this.name;  
  11.     }  
  12.     // 需要子类覆写clone方法  
  13.     public Object clone() throws 
    CloneNotSupportedException {  
  14.         return super.clone();       //
    具体的克隆操作由父类完成
     
  15.     }  
  16.     public String toString() {  
  17.         return "姓名:" + this.getName();  
  18.     }  
  19. };  
  20. public class CloneDemo01 {  
  21.     public static void main(String[] args) 
    throws Exception {  
  22.         Person p1 = new Person("张三");  
  23.         Person p2 = (Person) p1.clone();  
  24.         p2.setName("李四");  
  25.         System.out.println("原始对象:" + p1);  
  26.         System.out.println("克隆之后的对象:" + p2);  
  27.     }  
  28. }

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee