自验证:创建Class Student两个类, Student中含有Class对象
public class Class implements Cloneable {public String getName() {return name;}public void setName(String name) {this.name = name;}private String name;public Class(String name) {this.name = name;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}
public class Student implements Cloneable {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 Class getClazz() {return clazz;}public void setClazz(Class clazz) {this.clazz = clazz;}private String name;private int age;private Class clazz;public Student(String name, int age, Class clazz) {this.name = name;this.age = age;this.clazz = clazz;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}
测试代码:
public class Copy {public static void main(String[] args) throws CloneNotSupportedException {Class clazz = new Class("一班");Student student = new Student("张三", 18, clazz);Student newStudent = (Student) student.clone();student.getClazz().setName("二班");System.out.println("=== student===");System.out.println(student);System.out.println(student.getName());System.out.println(student.getAge());System.out.println(student.getClazz());System.out.println(student.getClazz().getName());System.out.println("=== newStudent===");System.out.println(newStudent);System.out.println(newStudent.getName());System.out.println(newStudent.getAge());System.out.println(newStudent.getClazz());System.out.println(newStudent.getClazz().getName());}
}
输出:
可以看到不同的Student对象,但是有相同的Class对象
修改Student clone方法:
@Overrideprotected Object clone() throws CloneNotSupportedException {Student student = (Student) super.clone();student.setClazz((Class) clazz.clone());return student;}
可以看到不同的class对象,不同的值:
知识来源:
【23版面试突击】什么是浅拷贝和深拷贝_哔哩哔哩_bilibili
强引用、弱引用介绍:
https://www.cnblogs.com/Scott007/archive/2013/05/15/3080739.html