浅拷贝定义
在拷贝一个对象时,对对象的基本数据类型的成员变量进行拷贝,但对引用类型的成员变量只进行引用的传递,并没有创建一个新的对象,当对引用类型的内容修改会影响被拷贝的对象。简而言之:浅拷贝仅仅复制所 拷贝 的对象,而不复制它所引用的对象。
浅拷贝样例如下
public class ShallowCopy {
public static void main(String[] args) throws CloneNotSupportedException {
Teacher teacher = new Teacher();
teacher.setName("KONG");
Student student = new Student();
student.setName("TOM");
student.setAge(18);
student.setTeacher(teacher);
Student studentCopy = (Student) student.clone();
student.setName("JERRY");
System.out.println("拷贝结束==");
System.out.println(studentCopy.getName());
System.out.println(studentCopy.getAge());
System.out.println(studentCopy.getTeacher().getName());
// 修改老师的信息
teacher.setName("WANG");
System.out.println("修改teacher之后==");
System.out.println("student的teacher为: " + student.getTeacher().getName());
System.out.println("studentCopy的teacher为: " + studentCopy.getTeacher().getName());
}
}
class Teacher implements Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Student implements Cloneable {
private String name;
private int age;
private Teacher teacher;
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 Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
demo运行结果如下
再看深拷贝
只要修改一下Student类的clone()方法即可
运行结果如下
总结
java的clone()方法是浅拷贝,对象内属性引用的对象只会拷贝引用地址,而不会将引用的对象重新分配内存,相对应的深拷贝则会连引用的对象也重新创建。