. Clone to implement the Cloneable interface;
. depth clone and Shallow clone
. Object. Clone ()
1. Clone©
Suppose there is now an employee object, employee Tobby =new employee ("Cmtobby", 5000), pass
Often we will have such assignment employee cindyelf=tobby, this time just simple copy a bit reference,cindyelf and tobby all point to the same object in memory, Such a cindyelf or tobby operation can affect each other. For example, if we change the value of the salary field through the Cindyelf.raisesalary () method, then tobby through the Getsalary () method is the value of the modified Salary field, which is obviously not what we would like to see. We want to get an exact copy of the Tobby, while the two do not affect each other, and we can use clone to meet our needs. Employee Cindy=tobby.clone (), a new employee object is generated and has the same property values and methods as Tobby.
2. Shallow Clone&deep Clone
How is clone done? Object does not know what to do when cloning an object, it simply executes the domain-to-domain copy, which is shallow Clone. So, here's the problem. For employee, for example, there is a domain hireday is not a basic type of variable, but a reference variable, after cloning will produce a new date type of reference, It points to the same date object as the corresponding field in the original object, so that the Clone class shares part of the information with the original class, which is obviously unfavorable, as shown in the procedure:
At this point we need to do deep clone, special processing of those non-basic domains, such as the hireday in this example. We can redefine the Clone method and do special processing for hireday, as shown in the following code:
- class Employee implements Cloneable
- {
- Public Object Clone () throws Clonenotsupportedexception
- {
- Employee cloned = (employee) Super.clone ();
- Cloned.hireday = (Date) hireday.clone ()
- return cloned;
- }
- }
3. Protection mechanism of Clone () method
In Object Clone () is declared as protected, and doing so has some justification to the employee
Class as an example, through the declaration as protected, you can ensure that only the employee class inside can "clone" employee object, the principle can refer to my previous about public, protected, private study notes.
4. Use of the Clone () method
The use of the Clone () method is relatively simple, note the following points:
A when to use shallow clone, when to use deep clone, this main look at the specific object of the domain is what nature, basic type or reference variable
b The class to which the object calling the Clone () method belongs must implements the Clonable interface, or clonenotsupportedexception is thrown when the Clone method is called.
Clone in Java