First, shallow cloning of objects
Object Shallow clone to note the details:
- If an object needs to invoke clone's method clone, then the class to which the object belongs must implement the Cloneable interface.
- The Cloneable interface is just an identity interface, and there is no method.
- A shallow clone of an object is when an object is cloned, and if the object of another class is maintained in the cloned object, it is simply cloning the address of the other object, instead of cloning a copy of the other object.
- The shallow clone of the object is also not called to the constructor method.
In the person class, the address class is referenced, and we observe the result by a shallow clone:
classAddressImplementscloneable, serializable{String city; PublicAddress (String city) {Super(); This. City =City ; } } Public classPersonImplementscloneable, serializable{intID; String name; Address address; PublicPerson (intID, String name, address address) { Super(); This. ID =ID; This. Name =name; This. Address =address; } PublicString toString () {return"No.:" + This. id+ "Name:" + This. name+ "Address:" +address.city; } PublicObject Clone ()throwsclonenotsupportedexception{return Super. Clone (); }}
When we clone the P1, and then change the P2 city,p1 and P2 are changed, that is, the top of the 3rd: The object's shallow clone is when cloning an object, if the cloned object maintains another class of objects, this time just to clone the address of another object, Instead of cloning a copy of the other object.
Second, deep copy of Object
The deep cloning of an object is the process of using an object's input and output stream to write the object to a file before reading the object's information, which is called a deep clone of the object.
Deep copy copies the objects referenced by the object being copied over
Public classDemo2 { Public Static voidMain (string[] args)throwsException {Address address=NewAddress ("Shanghai"); Person Person1=NewPerson (1, "Xiaoshan", address); Writeobj (Person1); Person Person2=readobj (); Person2.address.city= "Henan"; System.out.println (Person1); System.out.println (Person2); } Public Static voidWriteobj (Person P)throwsexception{File File=NewFile ("D:\\obj.txt"); FileOutputStream FileOutputStream=Newfileoutputstream (file); ObjectOutputStream ObjectOutputStream=NewObjectOutputStream (FileOutputStream); Objectoutputstream.writeobject (P); } Public StaticPerson Readobj ()throwsException {File file=NewFile ("D:\\obj.txt"); FileInputStream FileInputStream=Newfileinputstream (file); ObjectInputStream ObjectInputStream=NewObjectInputStream (FileInputStream); return(person) objectinputstream.readobject (); }}
When we clone the P1, and then change the P2 's city,p1 will not change, that is, the address also copied a copy.
On the Cloning of objects