Prior to the http://www.cnblogs.com/lhppom/p/4857702.html in the deep cloning of Java learning, the depth of the difference is that only the object reference and copy object reference to the object pointed to, recently in the Java Core Technology Volume 1 , see the example of one of the clones, here again to make a supplement, its implementation is to clone the object in addition to the numeric or basic class of the domain, and then the reference to the new cloned object in the corresponding domain;
1 Public classPetImplementscloneable{2 String name;3 4 PublicPet (String name) {5 This. Name =name;6 }7 8 Public voidsetName (String name) {9 This. Name =name;Ten } One A PublicString toString () { - return"Its name is" +name; - } the - PublicPet Clone () { - Try { - return(Pet)Super. Clone (); +}Catch(clonenotsupportedexception e) { - //TODO auto-generated Catch block + e.printstacktrace (); A } at return NULL; - } - -}Pet Class
1 Public classMansImplementscloneable{2 String name;3 intAge ;4 Pet Pet;5 6 PublicMan (String name,intAge , pet Pet) {7 This. Name =name;8 This. Age =Age ;9 This. Pet =Pet;Ten } One A PublicMan Clone () { - Man m; - Pet p; the Try { -m = (man)Super. Clone (); -p = (Pet) This. Pet.clone (); -M.pet =p; + returnm; -}Catch(clonenotsupportedexception e) { + //TODO auto-generated Catch block A e.printstacktrace (); at } - return NULL; - } - - PublicString toString () { - return"The man named" + Name + "Who's is" + Age in+ "years old owns the pet which" +pet.tostring (); - } to}Man class
Public classWomanImplementscloneable {String name; intAge ; Pet Pet; PublicWoman (String name,intAge , pet Pet) { This. Name =name; This. Age =Age ; This. Pet =Pet; } PublicObject Clone () {object o; Try{o=Super. Clone (); returno; } Catch(clonenotsupportedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } return NULL; } PublicString toString () {return"The woman named" + name + "Who's is" + Age+ "years old owns the pet which" +pet.tostring (); }}Woman class
1 Public classClonecomparetest {2 3 Public Static voidMain (string[] args) {4Pet p =NewPet ("Jack");5Woman W1 =NewWoman ("Marry", 21, p);6Woman W2 =(Woman) W1.clone ();7W2.pet.setName ("Tom");8System.out.println ("W1:" +w1.tostring ());9System.out.println ("W2:" +w2.tostring ());Ten OnePet P1 =NewPet ("Michal"); AMans m1=NewMan ("Jack", 32, p1); -Man m2 =M1.clone (); -M2.pet.setName ("Gary"); theSystem.out.println ("M1:" +m1.tostring ()); -System.out.println ("m2:" +m2.tostring ()); - } - +}the similarities and differences of the Shades clones test class
In the test results, we can see that the effect of deep cloning is true:
W1:the woman named marry who are years old owns the pet which it name is Tom
W2:the woman named marry who are years old owns the pet which it name is Tom
M1:the man named Jack years old owns the pet which it name is Michal
M2:the man named Jack, who's years old owns, the pet which its name is Gary
An example of Java Deep clone learning