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 implementation of the shallow copy example System.out.println (OBJ1); System.out.println (OBJ2); System.out.println ("*****************");//serialization implementation of the deep copy test obj3=new test (new User ("Hxh", 24), 168); Bytearrayoutputstream bout=new Bytearrayoutputstream (); try {objectoutputstream obj=new ObjectOutputStream (bout); O Bj.writeobjECT (OBJ3);} catch (IOException e) {//TODO auto-generated catch Blocke.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 Blocke.printstacktrace ();} catch (ClassNotFoundException e) { E.printstacktrace ();}}}
Deep copy and shallow copy of Java