克隆就是复制,可以将一个对象的内容完整的复制下来
Object 类提供以下的方法,完成对象的克隆
protected Object clone() throws CloneNotSupportedException
对于克隆操作并不是每一个对象都应该具备的,在java中只有部份对象才有可能进行克隆的操作,但是这部份对象必须且个明确的说明。
如果希望被克隆的对象,那么其所在的类必须实现Cloneable接口,此接口没有定义任何的方法,所以此接口只是一个标识
package org.clonedemo;
class Person implements Cloneable{ //表示此类的对象可以被克隆
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return "姓名:"+this.getName()+"年龄:"+this.getAge();
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
public class CloneDemo01 {
/**
* @param args
* @throws Exception
*/
public static void main(String args[]) throws CloneNotSupportedException {
// TODO Auto-generated method stub
Person per1 = new Person("张三",20);
Person per2 = (Person)per1.clone();
per2.setName("王五");
per2.setAge(30);
System.out.println(per1);
System.out.println(per2);
}
}