Now clone is no longer a new word. With the advent of "Dolly", it is indeed a "fire" for a while. This concept also exists in Java, it allows us to easily create a copy of an object. Let's take a look at how the clone mechanism works in Java? 1. Clone & copy assume that there is currently an employee object, which is employee Toby = new employee ("cmtober", 5000). Usually we will assign this value to employee cindyelf = Tober, at this time, we simply copied the reference. Both cindyelf and Tober point to the same object in the memory. In this way, one operation of cindyelf or Tober may affect the other party. For example, if we use cindyelf. the raisesalary () method changes the value of the salary domain, so what tolobby obtains through the getsalary () method is the value of the modified salary domain. Obviously, this is not what we are willing to see. We hope to get a precise copy of Tober, and the two do not affect each other. At this time, we can use clone to meet our needs. Employee Cindy = Tober. Clone (), a new employee object is generated and has the same property value and method as Tobe. 2. How is shallow clone and deep cloneclone completed? Objects do not know anything about them when performing clone on an object. They simply execute the copy of the domain to the domain, which is shallow clone. In this case, the problem arises. Taking employee as an example, there is a reference variable in the hireday field, which is not a basic variable, after cloning, a new date type reference is generated, which directs 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, this is obviously unfavorable, as shown in the process: At this time, we need to perform deep clone and perform special processing on those non-basic fields, such as hireday in this example. We can redefine the clone method and perform special processing on hireday, as shown below: Code As shown in:
Class employee implements cloneable
{
Public object clone () throws clonenotsupportedexception
{
Employee cloned = (employee) Super. Clone ();
Cloned. hireday = (date) hireday. Clone ()
Return cloned;
}
}
3. The protection mechanism of the clone () method is declared as protected in the object. To do so, take the employee class as an example and declare it as protected, you can ensure that only the employee class can "clone" the employee object. For the principle, refer to my previous study notes on public, protected, and private. 4. The clone () method is easy to use. Pay attention to the following points: A. When to use shallow clone and when to use deep clone, this mainly depends on the nature of the object's domain, the basic type is still reference variable B. The class of the object that calls the clone () method must be implements clonable. Otherwise, clonenotsupportedexception will be thrown when the clone method is called.