Clone of objects in Java
1. Declare and implement the cloneable interface and rewrite the clone method. If this method is not overwritten, the clone method of the object cannot be called.
2. call the super. clone to get an object. If there is no problem with the clone Implementation of the parent class, all fields defined by the parent class have been cloned in the memory storage of the object, the value type fields and reference type fields in this class are also cloned, but the currently referenced type fields are all shortest copies.
3. Point the reference of the shortest copy to the new clone of the prototype object.
public class Person implements Cloneable {private String name;private Integer age;public Person(String strName, Integer iAge){this.name = strName;this.age = iAge;}@Overrideprotected Object clone() throws CloneNotSupportedException {// TODO Auto-generated method stubreturn super.clone();}}
public class Account implements Cloneable {private Person person;private Integer balance;public Account(Person p, Integer i){this.person = p;this.balance = i;}@Overrideprotected Object clone() throws CloneNotSupportedException {// TODO Auto-generated method stubAccount account =(Account) super.clone();account.person = (Person)this.person.clone();return account;}}
Note: The object. Clone method is protected (protected). This method is only visible in its subclass and package.