import java.util.*;
import java.io.*;
class User implements Serializable{
public String name;
public int age;
public User(String str,int num){
name=str;
age=num;
}
public String toString(){
return "Name:"+name+"\n"+"Age:"+age;
}
}
class Test implements Cloneable,Serializable{
public int height;
public User user;
public Test(User u,int num){
user=u;
height=num;
}
public String toString(){
return user+"\n"+"Height:"+height;
}
public Object clone(){
try {
return super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
public class ArtTracer{
public static void main(String[] args){
Test obj1=new Test(new User("cjc",25),170);
Test obj2=(Test)obj1.clone();
obj1.user.age=30;
//Cloneable实现的浅拷贝例子
System.out.println(obj1);
System.out.println(obj2);
System.out.println("*****************");
//序列化实现的深拷贝
Test obj3=new Test(new User("hxh",24),168);
ByteArrayOutputStream bout=new ByteArrayOutputStream();
try {
ObjectOutputStream obj=new ObjectOutputStream(bout);
obj.writeObject(obj3);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
obj3.user.age=40;
try {
ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
Test obj4=(Test)in.readObject();
System.out.println(obj3);
System.out.println(obj4);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
}