publicclassCloneTest{ publicstaticvoidmain(String[] args){ Person person = new Person(1, "jack"); System.out.println(person); Person clone = person.clone(); System.out.println(clone); } }
classPersonimplementsCloneable{ int age; String name;
// constructor + toString
@Override public Person clone(){ Person clone = null; try { clone = (Person)super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } }
publicclassCloneTest{ publicstaticvoidmain(String[] args)throws CloneNotSupportedException { Person person = new Person(1, "jack"); Address addr = new Address("shanghai"); person.addr = addr;
Person clone = person.clone(); addr.addr = "hangzhou";
publicclassCloneTest{ publicstaticvoidmain(String[] args)throws CloneNotSupportedException { Person person = new Person(1, "jack"); Address addr = new Address("shanghai"); person.addr = addr;
Person clone = person.clone(); addr.addr = "hangzhou";