First, let's take a look at the definition of the shortest copy and deep copy:
Shallow copy: assign values to the member variables of the newly created instance one by one using a known instance. This method is called shortest copy.
Deep copy: When a copy constructor of a class not only copies all non-referenced member variable values of an object, but also creates a new instance for referenced member variables, the instance value is initialized as a form parameter. This method is called Deep copy.
That is to say, the shortest copy only copies one object and transmits references. The instance cannot be copied. Deep COPY Copies all references to the object. It creates a new instance and copies the instance.
For the shortest copy, when the object's member variables are of the basic data type, the member variables of the two objects already have a bucket. The value assignment operation passes the value, so the shortest copy can copy instances. However, when the object's member variables are of the reference data type, the object cannot be copied.
An object exists.Person,CodeAs follows:
1 Public Class Person { 2 Private String name; 3 Private String sex; 4 Private Int Age; 5 6 Public Person (string name, string sex, Int Age ){ 7 This . Name = Name; 8 This . Sex = Sex; 9 This . Age = Age; 10 } 11 12 Public Person (person p ){ // Copy the constructor and copy the object. 13 This . Name = P. Name; 14 This . Sex = P. sex; 15 This . Age =P. Age; 16 } 17 }
The above objectPersonThere are three member variables.Name,Sex,Age. Two constructor methods. The second parameter is the object, which is called the copy constructor. It initializes the new object to the Instance value of the form parameter and enables object replication.
There is another object Asian,As follows:
1 Public Class Asian { 2 Private String skin; 3 Person; 4 5 Public Asian (string skin, person ){ 6 This . Skin = Skin; 7 This . Person = person; // Reference Assignment 8 } 9 10 Public Asian (Asian ){ // Copy the constructor and copy the object. 11 This (Asian. Skin, Asian. person ); 12 } 13 }
The above object also has two member variables, skinAndPersonObject
ForPersonObjects are as follows:
1Person p1 =NewPerson ("Li Si", "Mam", 23);2 3Person P2 =NewPerson (P1 );
When the preceding statement is called.P2The object willP1. The execution is as follows:
1Asian a1 =NewAsian ("yellow ",NewPerson ("Li Si", "Mam", 23));2 3Asian a2 =NewAsian (A1 );
for Asian objects:
New Asian (A1)RunAsianClass copy constructor, because the object Value assignment is a reference value assignment. MakeA1AndA2Reference the same object
For example:
WhenA1When you execute a statement that can change this valueA1This statement can also be used to changeA2Object member variables
If you execute the following statement:
A2.name =NewPerson (a1.name)
A newPersonObject
For example: