1. First: Let's start by introducing what cloning is!
Clones are also called copies: copies can be divided into: 1. Shallow copy 2. Deep copy.
PackageChenyang;ImportJava.util.*;/** * * @author65245 * To achieve cloning*/ Public classPersonImplementscloneable{PrivateString name; Private intAge ; PrivateString sex; PrivateList<string>friends; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicString Getsex () {returnsex; } Public voidsetsex (String sex) { This. Sex =sex; } PublicList<string>getfriends () {returnfriends; } Public voidSetfriends (list<string>friends) { This. Friends =friends; } PublicPerson Clone () {Try { //objects that inherit object//because it's called everything is the type of object, so we're going to have a strong turnPerson frend = (person)Super. Clone (); //create a stored collectionlist<string> list =NewArraylist<string>(); //loop Gets the value manually entered and assigns to the collection of list for(String Person: This. Getfriends ()) {List.add (person); } //frend.setfriends (list); returnfrend; } Catch(clonenotsupportedexception e) {e.printstacktrace (); return NULL; } }}
PackageChenyang;Importjava.util.ArrayList;Importjava.util.List;/*** Text of the test class * *@author65245 **/ Public classText { Public Static voidMain (string[] args) {//1. Create a direct assignment to the collectionPerson person =NewPerson (); List<String> list =NewArraylist<string>(); List.add ("Hello"); List.add ("Word"); Person.setfriends (list); //2. The method of creating the clone of the person;Person Person1 =Person.clone (); System.out.println ("Person:" +Person ); System.out.println ("Person1:" +person1);}}
Prototype patterns of Java design patterns