public class Citation implements Cloneable{private Student stu;public Student getStu() {return stu;}public void setStu(Student stu) {this.stu = stu;}public void show() {System.out.println(stu.getName() + "同学:在2020学年第一学期中表现优秀,被评为三好学生。特发此状!");}@Overridepublic Citation clone() throws CloneNotSupportedException {Citation cloned = (Citation) super.clone();cloned.stu = stu.clone();return cloned;}
}
public class Student implements Cloneable {private String name;private String address;public Student(String name, String address) {this.name = name;this.address = address;}public Student() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overrideprotected Student clone() throws CloneNotSupportedException {return (Student) super.clone();}
}
上面两个是实体类,具体需要满足替换奖状的名字
@Testvoid contextLoads() throws CloneNotSupportedException {Citation c1 = new Citation();Student stu = new Student("张三", "西安");c1.setStu(stu);//复制奖状Citation c2 = c1.clone();//获取c2奖状所属学生对象Student stu1 = c2.getStu();stu1.setName("李四");//判断stu对象和stu1对象是否是同一个对象System.out.println("stu和stu1是同一个对象?" + (stu == stu1));System.out.println("c1和c2是同一个对象?"+ (c1==c2));c1.show();c2.show();}
问题是:在clone方法是浅拷贝的情况下,是否是只要实现cloneable接口,覆盖clone方法就可以实现深拷贝?有知道大佬回答一下。
注:大部分代码来源于黑马设计模式的原型模式部分