深层复制与浅层复制
深层复制:Java对象的深层复制是指Java对象A本身被复制成新对象B,同时A的属性也是被复制成新对象,赋值到A的各个属性上去,A与B的相同属性都引用到不同的对象。
浅层复制:A与B的属性没有复制成新的属性。比如: 虽然B与A的地址不同,但是B对象的成员对象与A对象对应的成员对象是同一个对象。
事例如下:
//手机实体类
package com.softstome.clone;
import java.io.Serializable;
public
class Phone implements Cloneable,Serializable{
private String color;
private String pinpai ; //品牌
private String[] gyss;
public Phone(){
}
public Phone(String color, String pinpai) {
super();
this.color = color;
this.pinpai = pinpai;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getPinpai() {
return pinpai;
}
public void setPinpai(String pinpai) {
this.pinpai = pinpai;
}
public String[] getGyss() {
return gyss;
}
public void setGyss(String[] gyss) {
this.gyss = gyss;
}
@Override
protected Phone clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return (Phone)super.clone();
}
}
//学生实体类
package com.softstome.clone;
import java.io.Serializable;
/*
* 实现Serializable
接口是为了通过
序列化的方式实现深层复制
*
* 实现Cloneable接口是为了通过 clone的方式实现实现深层复制
* */
public class Student implements Cloneable,Serializable {
private int stid;
private String stname;
private Phone phone;
public Student(){
}
public Student(int stid, String stname,Phone phone) {
super();
this.stid = stid;
this.stname = stname;
this.phone=phone;
}
public int getStid() {
return stid;
}
public void setStid(int stid) {
this.stid = stid;
}
public String getStname() {
return stname;
}
public void setStname(String stname) {
this.stname = stname;
}
public Phone getPhone() {
return phone;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
//重写克隆方法 实现对象的拷贝
@Override
protected Student clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Student stu=(Student)super.clone();
//要实现深层赋复制 ,必须要有这一句。(去掉则变成浅层拷贝)
stu.phone=phone.clone();
return stu;
}
}
//演示类
package com.softstome.clone;
public class TestClone {
/*
* 拷贝手机对象
* */
public void testClone1() throws CloneNotSupportedException {
Phone pn=new Phone();
String[] sz={"aa","bb"};
pn.setGyss(sz);
Phone pn1=(Phone)pn.clone();
System.out.println(pn +" "+pn1);
System.out.println(pn.getGyss()+" "+pn1.getGyss());
String[] sz1={"cc","dd"};
pn1.setGyss(sz1);
System.out.println(pn.getGyss()+" "+pn1.getGyss());
}
/*
* 拷贝(克隆)学生对象
* */
public void testClone2() throws CloneNotSupportedException{
Student stu=new Student(1,"张三",new Phone("红色", "
三星"));
Student stu1=(Student)stu.clone();
stu.setStname("张三1");
stu.getPhone().setColor("黑色");
System.out.println(stu.getStid()+" "+stu.getStname()+" " +stu.getPhone().getColor());
System.out.println(stu1.getStid()+" "+stu1.getStname()+" "+stu1.getPhone().getColor());
System.out.println(stu+" "+stu.getPhone()); //地址完全不同了,确实实现了克隆(浅层克隆)
System.out.println(stu1+" "+stu1.getPhone());
}
public static void main(String[] args) throws CloneNotSupportedException {
TestClone test= new TestClone();
test.testClone1();
//test.testClone2();
}
}