Java Clone (Clone) is one of the features of the Java language. This article mainly introduces how the Clone mechanism in Java works. Friends who need it can refer to it
Now Clone is no longer a new thing Word, with the emergence of "Dolly", this word is indeed "popular". After a while, there is also such a concept in Java, which allows us to easily "create" an object Come on, let’s take a closer look at how the Clone mechanism in Java works.
1. Clone&Copy
Suppose there is an Employee object now, Employee tobby =new Employee("CMTobby",5000), usually we will have such an assignment Employee cindyelf=tobby, this At that time, I simply copied the reference. Both cindyelf and tobby pointed to the same
object in the memory, so an operation of cindyelf or tobby may affect the other party.
propertiesvalues and methods as tobby.
2. Shallow Clone&Deep Clone
variable, but a reference variable, which will be generated after Clone A new reference of type Date points to the same Date object as the corresponding field in the original object. In this way, the cloned class shares part of the information with the original class, and this is obviously disadvantageous. In the process As shown in the figure:
At this time we need to perform deep Clone and perform special processing on those non-basic types of fields, such as hireDay in this example. We can redefine the Clone method and perform special processing on 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. The protection mechanism of the Clone() method
Clone() is declared as protected in Object. This makes sense. Take the Employee class as an example. By declaring it as protected, you can ensure that only the Employee class can "clone" the Employee object. For the principle, you can refer to my previous study notes on public, protected, and private.4. The use of Clone() method
The use of Clone() method is relatively simple, just 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 domain of the specific object. The basic type is still reference variableb. The class (Class) to which the object calling the Clone() method belongs must implement Clonableinterface, otherwise a CloneNotSupportedException will be thrown when the Clone method is called.
The above is the detailed content of Briefly describe the clone() method involved in shallow cloning and deep cloning in Java. For more information, please follow other related articles on the PHP Chinese website!