+ stud.getSubj().getName());
//Clone Object
Student clonedStud = (Student) stud.clone();
System.out.println("Cloned Object: " + clonedStud.getName() + " - "
+ clonedStud.getSubj().getName());
stud.setName("Dan");
stud.getSubj().setName("Physics");
System.out.println("Original Object after it is updated: "
+ stud.getName() + " - " + stud.getSubj().getName());
System.out.println("Cloned Object after updating original object: "
+ clonedStud.getName() + " - " + clonedStud.getSubj().getName());
}
}
输出结果是:
[java]
Original Object: John - Algebra
Cloned Object: John - Algebra
Original Object after it is updated: Dan - Physics
Cloned Object after updating original object: John - Physics
Original Object: John - Algebra
Cloned Object: John - Algebra
Original Object after it is updated: Dan - Physics
Cloned Object after updating original object: John - Physics
用java 实现深复制示例
只需要把上例的Student类的clone 方法修改如下:
[java]
class Student implements Cloneable {
//Contained object
private Subject subj;
private String name;
public Subject getSubj() {
return subj;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Student(String s, String sub) {
name = s;
subj = new Subject(sub);
}
public Object clone() {
//Deep copy
Student s = new Student(name, subj.getName());
return s;
}
}
class Student implements Cloneable {
//Contained object
private Subject subj;
private String name;
public Subject getSubj() {
return subj;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Student(String s, String sub) {
name = s;
subj = new Subject(sub);
}
public Object clone() {
//Deep copy
Student s = new Student(name, subj.getName());
return s;
}
}修改后运行结果如下:
[java]
Original Object: John - Algebra
Cloned Object: John - Algebra
Original Object after it is updated: Dan - Physics
Cloned Object after updating original object: John - Algebra
Original Object: John - Algebra
Cloned Object: John - Algebra
Original Object after it is updated: Dan - Physics
Cloned Object after updating original object: John - Algebra
使用序列化实现深复制
请看如下示例:
[java]
public class ColoredCircle implements Serializable {
private int x;
private int y;
public ColoredCircle(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "x=" + x + ",y=" + y;
}
}
public class ColoredCircle implements Serializable {
private int x;
private int y;
public ColoredCircle(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "x=" + x + ",y=" + y;
}
}
[java]
public class DeepCopy {
static public void main(String[] args) {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
// create origi