简单的说就是浅拷贝只拷贝对象的地址
深拷贝对象引用全拷贝
代码说明:
Student s = new Student("张三", 20);
//浅拷贝
Student s1 = s;
System.out.println("s的地址:" + s);
System.out.println("s1的地址" + s1);
System.out.println("-----------------------");
System.out.println("s name is:" + s.getName());
System.out.println("s name is" + s1.getName());
//修改对象属性,拷贝对象属性也发生改变
s1.setName("张三 is no ");
System.out.println("s name is:" + s.getName());
System.out.println("s name is" + s1.getName());
相当于只把地址引用拷了一份,而堆内存中的对象指的是同一个
深拷贝 :
第一种方式: 在通过构造函数对象时,对象的地址及属性修改互不影响
Student s = new Student("张三", 20);
Student s1 = new Student("李四", 10);
System.out.println("s:" + s);
System.out.println("s1:" + s1);
s:part01.Student@16e8e0c
s1:part01.Student@18e541e
第二种方式: 通过clone()方法实现深拷贝,重写clone()方法,两个Student对象隔离