The copy of programming languages can be divided into reference copy, shallow copy and deep copy.
It is relatively simple to reference copy. We direct a reference to an object, that is, a reference to copy. Referencing copy will not create an object, but will only point the reference to an existing object. The Code is as follows:
Object O1 = new object (); <br/> Object O2 = O1;
The shortest COPY method is the default COPY method in Java. When the clone () method is called, Java performs shortest copy on the object, copy the basic data type, but do not copy the reference inside the object. That is to say, the reference in the new object attribute after copy still points to the attribute of the original object. The shortest copy code is as follows:
Class Province implements cloneable {<br/> private string name; </P> <p> Public String getname () {<br/> return name; <br/>}</P> <p> Public void setname (string name) {<br/> This. name = Name; <br/>}</P> <p> Public province () {<br/> super (); <br/> // todo auto-generated constructor stub <br/>}</P> <p> Public province (string name) {<br/> super (); <br/> This. name = Name; <br/>}</P> <p> @ override <br/> Public object clone () throws clonenotsupportedexception {<br/> // todo auto-generated method stub <br/> return Super. clone (); <br/>}</P> <p> @ override <br/> Public String tostring () {<br/> // todo auto-generated method stub <br/> return name. tostring (); <br/>}</P> <p>}
Deep copy is to clone the references in the new object, that is, to create a new object. The principle of implementation is to call the clone method for references in the object when writing the clone method, the Code is as follows:
Class city implements cloneable {<br/> private string name; </P> <p> Public String getname () {<br/> return name; <br/>}</P> <p> Public void setname (string name) {<br/> This. name = Name; <br/>}</P> <p> private province; </P> <p> Public province getprovince () {<br/> return province; <br/>}</P> <p> Public void setprovince (province) {<br/> This. province = province; <br/>}</P> <p> Public City (string name, Province province) {<br/> super (); <br/> This. name = Name; <br/> This. province = province; <br/>}</P> <p> Public City () {<br/> super (); <br/> // todo auto-generated constructor stub <br/>}</P> <p> @ override <br/> Public object clone () throws clonenotsupportedexception {<br/> // todo auto-generated method stub <br/> city City = (city) super. clone (); <br/> city. province = (province) province. clone (); <br/> return city; <br/>}</P> <p> @ override <br/> Public String tostring () {<br/> // todo auto-generated method stub <br/> return province. tostring () + ":" + name. tostring (); <br/>}</P> <p>}