Detailed description of the clone method in Java: prototype mode (1)
Create an object in Java
As the name implies, clone is replication. in Java, the clone method is called by an object, so the object will be copied. To copy an object, you must first allocate a space of the same size as the source object and create a new object in the space. How can I create objects in java?
So what are the similarities and differences between the two methods? The new operator is intended to allocate memory. When the program executes the new operator, it first looks at the type behind the new operator. Only by knowing the type can we know how much memory space to allocate. After the memory is allocated, call the constructor to fill in the various fields of the object. This step is called object initialization. After the constructor returns the result, an object is created and Its Reference address can be set) publish to the outside, and you can use this reference to manipulate this object externally. In the first step, clone is similar to new. It allocates memory. When the clone method is called, the allocated memory is the same as the source object, that is, the object that calls the clone method, then, use the corresponding fields in the original object to fill in the fields of the new object. After the filling is complete, the clone method returns, and a new identical object is created, you can also publish the reference of this new object to the external.
Copy object or copy reference
In Java, the following code is very common:
- Person p = new Person(23, "zhang");
- Person p1 = p;
- System.out.println(p);
- System.out.println(p1);
When Person p1 = p; is a new object created after execution? First, check the printed result:
Com. pansoft. zhangjg. testclone. Person @ 2f9ee1ac
Com. pansoft. zhangjg. testclone. Person @ 2f9ee1ac
As you can see, the printed Address values are the same. Since the addresses are the same, they must be the same object. P and p1 are just references. They all point to the same object Person (23, "zhang "). This phenomenon can be called reference replication. For the distinction between references and objects, refer to my previous article on why strings in Java are immutable? -String source code analysis, which describes the distinction between references and objects ). After the above code is executed, the scenario in the memory is shown in:
The following code clones an object.
- Person p = new Person(23, "zhang");
- Person p1 = (Person) p.clone();
- System.out.println(p);
- System.out.println(p1);
The printed results show that the addresses of the two objects are different. That is to say, a new object is created, instead of assigning the original object address to a new reference variable:
Com. pansoft. zhangjg. testclone. Person @ 2f9ee1ac
Com. pansoft. zhangjg. testclone. Person @ 67f1fba0
After the above code is executed, the scenario in the memory is shown in: