java:对象的复制(深复制和浅复制)

1、浅复制表示复制目标对象本身,并不会复制目标对象的引用

java:对象的复制(深复制和浅复制)

2、深复制表示复制目标对象本身,并且复制目标对象的引用

java:对象的复制(深复制和浅复制)


3、对象复制的步骤:

    3.1:实现Cloneable这个标志接口

    3.2:重写Object类的clone方法,并将该方法访问修饰符改成Public

    3.3:必须调用父类的clone方法,因为可以识别要复制对象的类型等   super.clone();

4:也可以利用序列化和反序列化来实现深复制   



public class clone {


public static void main(String[] args) throws CloneNotSupportedException {
Student s1=new Student();
s1.setAge(20);
s1.setName(new Teacher());

Student s2=(Student)s1.clone();
//此行代码可以证明浅赋值    因为两个对象的地址一样
System.out.println(s1.getName()==s2.getName());

System.out.println("------------------------------------------");

Student2 s3=new Student2();
s3.setName(s1);
Student2 s4=(Student2)s3.clone();
//此行代码可以证明深赋值    因为两个对象的地址不一样
System.out.println(s4.getName()==s3.getName());
}


}


//对象的浅复制
class Student implements Cloneable{
private int age;
private Teacher tname;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Teacher getName() {
return tname;
}
public void setName(Teacher name) {
this.tname = tname;
}

@Override
public Object clone() throws CloneNotSupportedException {
Object obj=super.clone();
return obj;
}
}


class Teacher{

}




class Student2 implements Cloneable{
private int age;
private Student tname;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student getName() {
return tname;
}
public void setName(Student name) {
this.tname = name;
}

@Override
public Object clone() throws CloneNotSupportedException {
Student2 obj=(Student2)super.clone();
obj.tname=(Student)this.tname.clone();
return obj;
}
}