Cloning in Java (clone)

Source: Internet
Author: User

Interpreting clones

In the programming process, we often encounter the following situations: Suppose that there is an object, and there is a need for an instance like object Object2, emphasizing that object and Object2 are two separate instances, but at the beginning, They are in the same state (the values of attribute fields are the same), similar to identical twins. In general, the practice is to re-object2 a new object, the field value of object is given to Object2, it can be said that this method is very earth, we can use the Clone method to clone an object-like object2, very efficient.

misunderstanding: Some people think that the reference to the object is directly assigned to OBJECT2 to solve the problem, that is: object2=object; In this case two references still point to the same object, not two objects.

The two classes in Java that are related to cloning are the clone methods in the Cloneable interface and the object class, each of which is implemented by the collaboration of the two. First look at the description of the Clone method in the Java API doc about the Cloneable interface and the object class:

Java.lang.Cloneable Interface ( the following source cited JAVATM 2 Platform standard Ed. 5.0 API DOC)

This class implements the Cloneable interface to indicate that the Object.clone () method can legitimately replicate the class instance by field. Invoking the Clone method of Object on an instance that does not implement the Cloneable interface causes the clonenotsupportedexception exception to be thrown.

By convention, a class that implements this interface should use a public method to rewrite the Object.clone (which is protected). See Object.clone () For more information about overriding this method.

Note that this interface does not contain a clone method. Therefore, it is not possible to clone an object because it implements this interface. Even if the Clone method is a reflexive call, there is no guarantee that it will succeed.

Interpretation: The Cloneable interface has no method, only a flag interface (tagging interface), to have cloning capability, the class that implements the Cloneable interface must override the Clone method inherited from object and call the object's The Clone method (see the definition below Object#clone), the overridden method should be public. For example (standard notation):

12345678910111213141516171819202122232425 class CloneClass implements Cloneable{  public int aInt; //重写clone方法 public Object clone(){   CloneClass o = null;   try{    o = (CloneClass)super.clone();   }catch(CloneNotSupportedException e){    e.printStackTrace();   }   return o;  } }

protected native Object clone () throws Clonenotsupportedexception ( The following source cited JAVATM 2 Platform standard Ed. 5.0 API DOC)

Creates and returns a copy of this object. The exact meaning of a "copy" may depend on the class of the object. In general, for any object x, if an expression:

X.clone ()! = x is correct, the expression: X.clone (). GetClass () = = X.getclass () will be true, but these are not absolute conditions.

Typically: X.clone (). Equals (x) will be true, but this is not an absolute condition.

By convention, the returned object should be obtained by calling Super.clone. If a class and all of its superclass (except Object) adhere to this Convention, then X.clone (). GetClass () = = X.getclass ().

By convention, the object returned by this method should be independent of the object (the object being cloned). To achieve this independence, it is necessary to modify one or more fields of the object before Super.clone returns the object. This usually means that you want to copy all the mutable objects that contain the internal "deep structure" of the object being cloned and replace the references to those objects with references to the copy. If a class contains only basic fields or references to immutable objects, you typically do not need to modify the fields in the object returned by Super.clone.

The Clone method of the Object class performs a specific clone operation. First, if the class of this object cannot implement interface cloneable, then Clonenotsupportedexception will be thrown. Note: All arrays are considered to implement Interface cloneable. Otherwise, this method creates a new instance of the class for this object and, as it is assigned, initializes all fields of the object strictly using the contents of the corresponding field of the object, and the contents of those fields are not self-cloned. Therefore, this method performs a "shallow copy" of the object, not a "deep copy" operation.

The object class itself does not implement interface cloneable, so calling the Clone method on an object that is class object will cause an exception to be thrown at run time.

Interpretation: The Clone method in object is native, which also explains the "efficient" mentioned above. Classes that implement the Cloneable interface implement the cloning capability (standard notation) through Super.clone () calls. As mentioned earlier, clones are copied by attribute fields, if the object's property value is a mutable reference (immutable: such as a primitive type, a final type, variable: such as a reference to an object, an array reference), then the original object and the cloned object will not remain independent, because one of their properties references an object together, which is " Shallow copy ", this is not what we want, normal what we need is" deep copy ", that is, to further clone,for the properties of the object example:

1234567891011121314151617 public class A implements Cloneable {    public String a[];    public A(){        a=new String[2];    }    public Object clone() {        A o = null;        try {            o = (A) super.clone(); o.a=(String[])a.clone();//属性a的克隆,实现A类的深度克隆        } catch (CloneNotSupportedException e) {            e.printStackTrace();        }        return o;    }}

  

If the public String a[] is changed to public b a[], if we want to get a thorough copy, we need class B to implement the Cloneable interface, especially when encountering complex types, such as vectors, to pay attention to the objects in the container, as for you The need for deep replication and how many layers to replicate is based on specific needs.

Related knowledge

List of Java modifier access rights

T1: Access permissions for modifiers

This and super usage

The This keyword represents the object itself, and the main uses in the program are the following:

L Use the This keyword to refer to member variables

L Use the This keyword to refer to other construction methods within its own constructor

L Use the This keyword to represent objects of your own class

L Use the This keyword to refer to member methods

The Super keyword, which uses the Super keyword to refer to the contents of the parent class in the child class. The main forms of use are as follows:

L reference the construction method of the parent class within the constructor of the subclass

L call a member method in a parent class in a subclass

L call a member variable in a parent class in a subclass

Cloning in Java (clone)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.