通过 Cloneable 接口实现克隆对象
Person 类
public class Person implements Cloneable{ // 4.实现Cloneable接口
public int id;
Money m = new Money();
public Person(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
'}';
}
@Override // 1.想使用clone方法,需重写Object类的clone方法
protected Object clone() throws CloneNotSupportedException {
// return super.clone(); 浅拷贝
Person tmp = (Person) super.clone(); // 先新建对象进行浅拷贝
tmp.m = (Money) this.m.clone(); // 再通过tmp.m 使得 类中对象 进行拷贝
return tmp; // 深拷贝
}
}
Money 类
public class Money {
public double money = 9.9;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
测试类
public class Test {
public static void main(String[] args) throws CloneNotSupportedException { // 2.main方法声明异常
Person person1 = new Person(1);
Person person2 = (Person) person1.clone(); // 3.调用重写方法时需强转类型
System.out.println(person1.m.money);
System.out.println(person2.m.money);
System.out.println("====================");
person2.m.money = 99.9;
System.out.println(person1.m.money); // 99.9
System.out.println(person2.m.money); // 99.9
}
}

参与讨论
(Participate in the discussion)
参与讨论