浅拷贝
浅拷贝会创建一个新对象,如果这个对象的属性是基本类型,那么拷贝的就是基本数据类型的值。如果这个对象的属性是引用数据类型,那么拷贝的就是对象的引用地址。
//实现Cloneable接口 重写clone()方法
class Thcher implements Cloneable{
String name;
public Thcher() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Thcher clone() throws CloneNotSupportedException {
return (Thcher) super.clone();
}
}
class Student implements Cloneable {
int age;
//拷贝Thcher对象,拷贝引用地址。
Thcher thcher;
public Student() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Thcher getThcher() {
return thcher;
}
public void setThcher(Thcher thcher) {
this.thcher = thcher;
}
//浅拷贝,直接调用父类方法
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
}
public class CopyTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student();
student.age = 1;
student.thcher = new Thcher();
student.thcher.name = "xiaowang";
Student stu2 = student.clone();
//拷贝会创建一个新对象
System.out.println(stu2 == student);
//对象中的引用数据类型的地址不变
System.out.println(stu2.thcher == student.thcher);
}
}
深拷贝
深拷贝会将对象的所有属性都浅拷贝一份。比如:对于引用变量来说,他会创建一个新的引用,拷贝的对象指向这个新的引用。
深拷贝相比于浅拷贝速度较慢并且花销较大
//实现Cloneable接口 重写clone()方法
class Thcher implements Cloneable{
String name;
public Thcher() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Thcher clone() throws CloneNotSupportedException {
return (Thcher) super.clone();
}
}
class Student implements Cloneable {
int age;
Thcher thcher;
public Student() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Thcher getThcher() {
return thcher;
}
public void setThcher(Thcher thcher) {
this.thcher = thcher;
}
//深拷贝,重写clone方法
@Override
protected Student clone() throws CloneNotSupportedException {
Student student = new Student();
student.thcher = this.thcher.clone();
student.age = this.age;
return student;
}
}
public class CopyTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student();
student.age = 1;
student.thcher = new Thcher();
student.thcher.name = "xiaowang";
Student stu2 = student.clone();
//深拷贝,创建一个新对象
System.out.println(stu2 == student);
//深拷贝,对象中的引用数据类型的地址不同
System.out.println(stu2.thcher == student.thcher);
}
}