[java]代码库
class Person implements Cloneable {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "姓名:" + this.name + ",年龄:" + this.age;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
};
public class CloneDemo {
public static void main(String[] args) throws Exception {
Person p1 = new Person("张三", 10);
Person p2 = (Person) p1.clone();
p2.setName("李四");// 克隆后修改p2,不影响p1
p1.setAge(20); // 克隆后修改p1,不影响p2
System.out.println("原始对象:\t" + p1);
System.out.println("克隆之后的对象:\t" + p2);
}
}