in program development if an object a already exists, you now need an object B that is exactly the same as the A object, and modify the property value of the B object, but the original property value of the A object cannot be changed. This is, if you modify the property value of a B object by using the object assignment statement provided by Java, the property value of the A object will also be modified. Then you should think of using the Java clone method to achieve. There are two situations in which the first case is that all the properties in the object are basic types without reference types, so you can just rewrite the clone method of the Cloneable interface, and the second case is that there are reference types for other objects in the object, but only the former clones will be invalidated. For example, the following code:
the output is:before cloning:the information for employee 1 is:Name: Zhagnsan, Age: 17, Address: Country: China, Province: Jilin, City: Changchun
After cloning:
The information for employee 2 is:
Name: Lisi, Age: 17, Address: Country: Zhongguo, Province: Hebei, City: Shijiazhuang
The information for employee 1 is:
Name: Zhagnsan, Age: 17, Address: Country: Zhongguo, Province: Hebei, City: Shijiazhuang
and really want the result, employee 1 of information should not change. Employee 1 The reason for the change is that shallow cloning is not enough to clone a reference type, so deep cloning is needed to make the following adjustments to the code:1, address also need to implement the Cloneable interface, and then rewrite the address class clone method. 2, the employee's Clone method plus employee.address = Address.clone ();
the output at this time is: The information for employee 1 is:
Name: Zhagnsan, Age: 17, Address: Country: China, Province: Jilin, City: Changchun
After cloning:
The information for employee 2 is:
Name: Lisi, Age: 17, Address: Country: Zhongguo, Province: Hebei, City: Shijiazhuang
The information for employee 1 is:
Name: Zhagnsan, Age: 17, Address: Country: China, Province: Jilin, City: Changchun
Superficial cloning and deep cloning in Java