Java Object Copy FAQ
@author Ixenos
about clone[object Copy]
In the actual programming process, sometimes we will encounter a situation: When you have an object A, at some point, a has saved the corresponding property values, and the values themselves are valid, this time may need a and a exactly the same object B, and when the value of the property in B is changed, The attribute values in a are not affected and can be understood as a and b independent, but the initialization of B is not based on the initialization of the object that we normally create, and B's initialization data is entirely from a.
Everyone who knows about the Java storage model understands that in Java, if an assignment is taken for two object references, only two references are directed to the same object (that is, value passing , not reference passing). If the object property of one of the references changes, it will affect the change of the other object property, so the object assignment statement of the Java language itself cannot complete the above requirement. At such times, it is necessary to use the generic method clone () inside the object class, which needs to be explained here:
the object created by the Clone () method is a new object that can be thought of as a copy of the source object, but in the memory heap, the JVM assigns the copy new Object storage space to hold all the states of the object. the only difference between the copy and the object created with the new operator is the initial value, which is not the default value of the member in the object, but the same value as the member of the source object's state at the moment .
This code below is the use of the Clone method:
Public classTesting { Public Static voidMain (String args[]) {aclass Class1=NewAClass (); class1.a= 12; AClass Class2=(AClass) Class1.clone (); System.out.println (class2.a); System.out.println (Class1==Class2); }}classAClassImplementscloneable{ Public intA = 0; PublicObject Clone () {AClass o=NULL; Try{o= (AClass)Super. Clone (); }Catch(Clonenotsupportedexception ex) {ex.printstacktrace (); } returno; }} above this code runs the result output as:12falseView Code
What is known is that a AClass object is successfully copied, the reference to the object is Class1, and the reference to the Copy object is Class2, the two references are output to false through = =, proving that the two references are not pointing to the same object. And the value of a in the Copy object is the same as the value of a in the object referenced by Class1, which is 12, so the copy of the object is completed successfully.
several points to note in the clone process of an object
1. The class wishing to provide the object clone function must implement the Cloneable interface , which is located in the Java.lang package
2. The class that wants to provide the object clone function must overload the Clone () method, which can be seen in the overloaded procedure:super.clone (); that is, regardless of the inheritance structure of the Clone class, We call the Clone () method of object directly or indirectly when copying objects. And careful attention can see that the Clone method of the object is protected domain , that is, this method only the subclass of object can be called , and at the time of overloading the Clone method modifier changed to public
3. It is also important that the Clone () method in the object source code is the native method , and generally, thenative method is much more efficient for the JVM than the common method in Java. , which is why we use the Clone () method of object when copying an object, rather than using new.
4. The Cloneable interface is the same as theserialization interface when we write an IO program, which is a flag that does not contain any methods, and is primarily intended to detect the Clone method in the object class . If the class we define wants to implement the copy function, but does not implement the interface and invokes the Clone method of object, then the exception error in the CATCH block in the statement is thrown, and the clonenotsupportedexception is raised.
about Shallow copy
In the object clone process, the shallow copy is also called " Shadow Clone", first look at a piece of code:
//this defines a class firstclassaclass{ Public intA; PublicAClass (intA) { This. A =A;} Public voidChange () {A + = 12;} PublicString toString () {return"A Value is" + This. A;}}//defines a clone class that contains AClass object referencesclassBclassImplementscloneable{ Public intA = 12; PublicAClass obj =NewAClass (11); PublicObject Clone () {Bclass object=NULL; Try{Object= (Bclass)Super. Clone (); }Catch(Clonenotsupportedexception ex) {ex.printstacktrace (); } returnobject; }} Public classTestclone { Public Static voidMain (String args[]) {bclass Class1=NewBclass (); class1.a= 15; System.out.println (class1.a); System.out.println (Class1.obj); Bclass Class2=(Bclass) Class1.clone (); class2.a= 22; Class2.obj.change (); System.out.println (class1.a); System.out.println (Class1.obj); System.out.println (class2.a); System.out.println (Class2.obj); This code will have the following output when running the upper part:15A Value is1115//Copy Here is successful.A Value is 23//!!! No, there is no call to the change method of obj inside Class1, so you should not modify the value of the variable A in the Class1 inside obj "original"22A Value is23 View Code
Although the object referenced by Class2 is copied from Class1, the reference to obj and Class1 in Class2 is actually pointing to the same object, meaning that the copy was originally intended to copy an identical object, Objects inside the object should also implement a copy operation, which is ultimately intended to ensure that the properties of the Class1 and Class2 itself, as well as the properties referenced in Class1 and Class2, are independent of each other in the various related operations after the copy, The above output proves that the variable a in Class1 and Class2 has been successfully copied, but the reference to the AClass object in Class1 and Class2 obj has been copied or pointed to the same object , so after the copy is finished, When invoking the change method of Class2 obj, it also modifies the value inside the object that obj points to in Class1. So in Java we refer to the above copy process as "shallow copy", also known as "Shadow Clone".
It can be known from this that in the case of the JVM object replication, the basic data type can be copied directly in this way, rather than the original type, so the copied object only copies the member variables of the basic data type inside the object. The more complex types of member variables do not produce copy effects as expected, which we call a "shallow copy."
about deep Copy
If we want to achieve the desired copy of the object, we need to use deep copy operation, it is a shallow copy based on the implementation of deep copy has two steps, with the above code as an example:
First step: Let AClass achieve the same clone function
The second step: in the clone operation of Bclass write a sentence: Object.obj = (aclass) obj.clone ();
about the keyword this, super
In the Java language class definition, there are two built-in objects, one is this, the other is super, and the meanings of the two objects are as follows:
This is a reference to the object itself that points to the object itself that the class instantiates;
Super is a reference to the parent class of that class, and if the class does not inherit from any class, then the class calls Super to refer to the object class
Here is a short code description:
classaclass{ PublicAClass (inta) {System.out.println ("A Init" +a); } Public voidFuninta) {System.out.println ("Fun int" +a); }}classBclassextendsaclass{Private intA = 24; Private Static intb = 11; PublicBclass () { This(12); //this.b = n; Super. Fun (12); } PublicBclass (inta) {Super(12); System.out.println ("B Init" + This. a); }}View Code
for the above code snippet do a few detailed instructions:
Super.fun (12): Use the Super keyword when accessing a member of a parent class in a subclass, but super cannot access the private member of the parent class;
Super (12): Subclass if you want to invoke the constructor of the parent class, you can call the Super (Param) method directly, but if the constructor of the parent class is called, it cannot be done in the other function blocks of the subclass, only in the constructor, and generally cannot and this (param) appear at the same time, about their use in the constructor, will be described in section 7;
//this.b=12: Although this remark is commented out, this sentence can be compiled by the JVM, where it is necessary to distinguish between calling a non-static member in a static block and calling a static member in a normal block. Calling a static member in a normal statement is a possible use of this. VAR, but it is generally not advocated because the static members are generally called in a unique way to use Class.var instead of This.var.
this (/this.a:this) invokes the constructor directly using the This (Param) method when calling its own member's constructor, and uses the latter if it is called a normal member.
*:this and super can not be run in the static block, whether static initialization blocks of static or static method blocks, can not appear inside this and super keyword, this is simple: static block is the class domain, That is, the contents of the static block are initialized when the class loader of the JVM first loads the class, and the entire process is initialized only once. This and super are operations of the object domain, this refers to the instance itself, not the class, and the same super refers to the instance of the parent class itself, not the class, so this and super is not able to appear in static method blocks of static. In fact, conceptually, static and this, super operation of the object is not the same, static is class, and super and this is the object, so the programming process must pay attention to this.
Java Object Copy FAQ