publicstaticvoidmain(String[] args)throws CloneNotSupportedException { Mark mark = new Mark(100,99); User user = new User("user",22,mark); User userClone = (User) user.clone(); System.out.println("原来的user:"+user); System.out.println("克隆的user:"+userClone); //修改引用类型的mark属性 user.mark.setMath(60); System.out.println("修改后原来的user:"+user); System.out.println("修改后克隆的user:"+userClone); } }
@Override public String toString(){ return"User{" + "name='" + name + '\'' + ", age=" + age + ", mark=" + mark + '}'; }
@Override protected Object clone()throws CloneNotSupportedException { User user = (User) super.clone(); user.mark = (Mark) this.mark.clone(); return user; }
publicstaticvoidmain(String[] args)throws CloneNotSupportedException { Mark mark = new Mark(100,99); User user = new User("user",22,mark); User userClone = (User) user.clone(); System.out.println("原来的user:"+user); System.out.println("克隆的user:"+userClone); //修改引用类型的mark属性 user.mark.setMath(60); System.out.println("修改后原来的user:"+user); System.out.println("修改后克隆的user:"+userClone); } }
@Override public String toString(){ return"User{" + "name='" + name + '\'' + ", age=" + age + ", mark=" + mark + '}'; } publicstaticvoidmain(String[] args)throws IOException, ClassNotFoundException { Mark mark = new Mark(100,99); User user = new User("user",22,mark);
ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(user);//序列化 ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bi); User userClone = (User) oi.readObject();//反序列化