class Money{
public double m = 12.5;
}
class Add implements Cloneable{
public Money money = new Money();
public int age;
public String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Add a = new Add();
Add b = (Add)a.clone();
}
}//这里是一个浅拷贝
以上方法是一个浅拷贝,若要拷贝需要具备一个条件,第一就是要拷贝的这个类要实现Clonable这个接口代表该类可以被拷贝,此时所进行的拷贝并不能将该对象完全拷贝,拷贝出来的moeny和this的moeny都指向同一个存储位置,如果要想修改moeny的值,无论是修改拷贝出来的还是原本的都会导致两个对象的moeny发生同步的变化
class M implements Cloneable{
public double price = 12.5;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Student implements Cloneable{
String name;
int age;
M m = new M();
@Override
protected Object clone() throws CloneNotSupportedException {
Student student = (Student) super.clone();
student.m= (M)student.m.clone();
return student;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", m=" + m.price +
'}';
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException{
Scanner scanner = new Scanner(System.in);
Student student1 = new Student(15,"刘杰");
Student student2 = (Student) student1.clone();
student2.m.price = 100.0;
System.out.println(student1.toString());
System.out.println(student2.toString());
}
}
以上就是一个深拷贝,此时再此将student1进行拷贝,拷贝之后的price指向一个新的存储位置,两个price就是相互独立的了