public class Person implements Cloneable {// 必须实现Cloneable接口
private String name=null;
public Person(String name){
this.name= name;
}
public void setName(String name){
this.name= name;
}
public String getName() {
returnname;
}
// 需要子类覆写clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();//具体的克隆操作由父类完成
}
public String toString() {
return"姓名:"+this.name;
}
}
/*克隆*/
Person p1 =new Person("张三");
Person p2 =null;
try{
p2 = (Person) p1.clone();
}catch(CloneNotSupportedException e) {
e.printStackTrace();
}
p2.setName("李四");
System.out.println("原始对象:"+ p1);
System.out.println("克隆之后的对象:"+ p2);