class Professor implements Cloneable { String name; int age; Professor(String name,int age) { this.name=name; this.age=age; } public Object clone() { Object o=null; try { o=super.clone(); } catch(CloneNotSupportedException e) { System.out.println(e.toString()); } return o; } } class Student implements Cloneable { String name; int age; Professor p;// 学生1和学生2的引用值都是一样的。 Student(String name,int age,Professor p) { this.name=name; this.age=age; this.p=p; } public Object clone() { Student o=null; try { o=(Student)super.clone(); } catch(CloneNotSupportedException e) { System.out.println(e.toString()); } //o.p=(Professor)p.clone(); 注释后为浅复制,s1和s2仍指向同一对象;去注释后为深复制 return o; }
public Object deepClone() throws IOException, ClassNotFoundException { //将对象写到流里 ByteArrayOutputStream bo=new ByteArrayOutputStream(); ObjectOutputStream oo=new ObjectOutputStream(bo); oo.writeObject(this); //从流里读出来 ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi=new ObjectInputStream(bi); return(oi.readObject()); }
} public class Main {public static void main(String[] args) { Professor p=new Professor("wangwu",50); Student s1=new Student("zhangsan",18,p); Student s2=(Student)s1.clone(); s2.p.name="lisi"; s2.p.age=30; System.out.println("name="+s1.p.name+","+"age="+s1.p.age);//学生1的教授成为lisi,age为30。 }}