Teacher tea=new Teacher("唐僧");
Student stu=new Student();
stu.teacher=tea;
System.out.println(stu);//Student{teacher=Teacher{name='唐僧'}}
Objectobj=stu.clone();//Student{teacher=Teacher{name='唐僧'}}
System.out.println(obj);
System.out.println("-------------------");
stu.teacher.name="阿旺";
System.out.println(obj);//Student{teacher=Teacher{name='唐僧'}}
System.out.println(stu);//Student{teacher=Teacher{name='阿旺'}}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Object clone() throws CloneNotSupportedException{
//克隆自身也要克隆关联的属性
Object obj = super.clone();//将当前对象克隆一份
Object objTeacher = this.teacher.clone();//将当前对象的teacher的属性克隆一遍
//将克隆出来的teacher对象值给克隆出来的Student对象中
((Student)obj).teacher=(Teacher)objTeacher;
return obj;
}
- 由于 Object 本身没有实现 Cloneable 接口,所以不重写 clone 方法并且进行调用的话会发生 CloneNotSupportedException 异常。
- clone() 方法是浅拷贝,对象内属性引用的对象只会拷贝引用地址,而不会将引用的对象重新分配内存,相对应的深拷贝则会连引用的对象也重新创建。
- Object clone() 方法用于创建并返回一个对象的拷贝。