一:浅拷贝
先创建一个对象将被拷贝对象中的每个成员变量中的值域原封不动的拷贝到新对象中
如果元对象中的成员都是内置类型的,浅拷贝没有什么危害
如果原对象中的成员包含引用类型的(PeopleMoney),浅拷贝有缺陷
源对象和新对象中的引用类型的成员变量将来指向的是同一份实体(地址相同)一个对象将该实体修改后,其他引用该实习的对象也被修改
//Cloneable 是标记接口
public class People implements Cloneable {
String name;
int age;
PeopleMoney p;
public People() {
}
public People(String name, int age, PeopleMoney p) {
this.name = name;
this.age = age;
this.p = p;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return name+","+age+","+p.money;
}
}
public class PeopleMoney {
int money;
public PeopleMoney() {
}
public PeopleMoney(int money) {
this.money = money;
}
}
public class PeopleTest {
public static void method() throws CloneNotSupportedException {
People p1=new People("张三",18,new PeopleMoney(4534646));
People p2=(People)p1.clone();
p1.age=20;
System.out.println(p1);
System.out.println(p2);
p2.age=30;
System.out.println(p1);
System.out.println(p2);
p1.p.money=1463434;
System.out.println(p1);
System.out.println(p2);
p2.p.money=9463431;
System.out.println(p1);
System.out.println(p2);
}
public static void main(String[] args) throws CloneNotSupportedException {
System.out.println("浅拷贝");
method();
}
}
二: 深拷贝
在clone时,如果对象中包含引用类型,就需要使用深拷贝 即:将对象的引用引用的实体再拷贝一份需要重写clone
public class Date implements Cloneable{
int year;
int month;
int day;
Time t;
public Date() {
}
public Date(int year, int month, int day, Time t) {
this.year = year;
this.month = month;
this.day = day;
this.t = t;
}
@Override
protected Date clone() throws CloneNotSupportedException {
Time T=new Time(t.hours,t.minutes,t.seconds);
return new Date(year,month,day,T);
}
@Override
public String toString() {
return year+"-"+month+"-"+day+"-"+t.hours+"-"+t.minutes+"-"+t.seconds;
}
}
public class Time {
int hours;
int minutes;
int seconds;
public Time(int hours, int minutes, int seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
}
public class CloneTest {
public static void method3() throws CloneNotSupportedException {
//在clone时,如果对象中包含引用类型,就需要使用深拷贝
//即:将对象的引用引用的实体再拷贝一份
//需要重写clone
Date a=new Date(2022,9,9,new Time(17,49,32));
Date b=(Date)a.clone();
a.day=10;
System.out.println(a);
System.out.println(b);
b.t.seconds=7;
System.out.println(a);
System.out.println(b);
}
public static void main(String[] args) throws CloneNotSupportedException {
System.out.println("深拷贝");
method3();
}
}