Java Cloneable document translation and complete instance Parsing

Source: Internet
Author: User

Java Cloneable document translation and complete instance Parsing

Title: java. lang. Cloneable parsing date: 14:26:01

Tags: java

Java. lang Interface Cloneable

All Known Subinterfaces: All Known Subinterfaces

AclEntry, Attribute, AttributedCharacterIterator, Attributes, CertPathBuilderResult, CertPathParameters, CertPathValidatorResult, CertSelector,

CertStoreParameters, CharacterIterator, CRLSelector, Descriptor, GSSCredential,

Name

Public interface Cloneable

A class implements the Cloneable interface to indicate to the Object. clone ()

Method that it is legal for that method to make a field-for-field copy

Instances of that class.


Invoking Object's clone method on an instance that does not implement

Cloneable interface results in the exception CloneNotSupportedException being

Thrown.


By convention, classes that implement this interface shocould override Object. clone

(Which is protected) with a public method. See Object. clone () for details on

Overriding this method.


Note that this interface does not contain the clone method. Therefore, it is not

Possible to clone an object merely by course ue of the fact that it implements this

Interface. Even if the clone method is invoked reflectively, there is no

Guarantee that it will succeed.

This class implements Cloneable interface to indicate that the Object. clone () method can copy the instance of this class in a legal way.

If the instance that calls the clone method does not have the implements Cloneable interface, CloneNotSupportedException Exception is thrown.

According to the habit, the classes of the Cloneable interface of implements needs to overload Object. clone (it is protected ).

Note that this interface does not contain the clone method. Therefore, it is impossible to clone an object after it is implemented. Even if you call the clone method through reflection, the call will not be successful.

Since: JDK1.0 See Also: CloneNotSupportedException, Object. clone ()


The above is directly translated from java doc, so it must be clear. Next, let's record a simple example of technical transformation.

/**

* Created by canglangwenyue on 12/5/14.

*/

Public class Person implements Cloneable {


Private int id;

Private String name;


Public String getName (){

Return name;

}


Public int getId (){

Return id;

}


Public void setId (int id ){

This. id = id;

}


Public void setName (String name ){

This. name = name;

}


@ Override

Protected Object clone (){


Person copy = null;


Try {

Copy = (Person) super. clone ();

Copy. clone (). getClass (). getName ();


} Catch (CloneNotSupportedException e ){

E. printStackTrace ();

} Finally {

Return copy;

}



}


@ Override

Public boolean equals (Object obj ){

Return super. equals (obj );

}


/**

* Test of referencing and copying

*/


Public static void referenceTest (){

Person person = new Person ();


Person. setId (1 );

Person. setName ("WenYue ");


Person copy = person;


If (copy. equals (person ))

System. out. println ("the copied person and copy are the same object ");

Else

System. out. println ("the copied person and copy are not the same object ");


System. out. println (person );

System. out. println (copy );

System. out. println (person. getName ());

System. out. println (copy. getName ());


}


/**

* For the Object clone test method, it is detected that the clone is implemented by shortest copy.

*/

Public static void cloneTest (){

Person person = new Person ();


Person. setId (1 );

Person. setName ("WenYue ");


Person copy = null;


Copy = (Person) person. clone ();


If (copy. equals (person ))

System. out. println ("clone person and copy are the same object ");

Else

System. out. println ("clone's person and copy are not the same object ");


System. out. println (person );

System. out. println (copy );

System. out. println (person. getName ());

System. out. println (copy. getName ());


String result = person. getName () = copy. getName ()? "Clone is a shallow copy": "clone is a deep copy ";

System. out. println (result );

}


Public static void main (String [] args ){

/* Test clone */

CloneTest ();


/* Test reference copying */

ReferenceTest ();


}



}

The execution result of the main function is shown as follows:


Now let's explain the test code.

We can see that two test methods are executed in the main function, cloneTest () and referenceTest (). The first Object that implements Cloneable interface is used to test the clone () method; the reason for adding the second method is to make the object shortest copy, that is, clone (the default object copy in java is shortest copy )., It is easier to understand and compare with the referenced copy.

1. from the execution results of this code, we can clearly see that the clone implementation copy creates a new object for copy (the address in the memory is different), and the reference copy, just copy the address of the original object to the new object, so after going straight, the person and copy point to the same address space.

Description about clone, which is a shortest copy by default

2. First, because id is the basic data type, there is no doubt about its copy. Just copy a 4-byte integer. However, name is of the String type, and name is only a reference pointing to a real String object. The reason why clone is a shortest copy by default is, during clone, the clone method only copies the reference value of the String object to the name field of the new copy object. Instead of re-creating a String object in the memory, and let the name field of the copy object point to it. The proof is as follows:


String result = person. getName () = copy. getName ()? "Clone is a shallow copy": "clone is a deep copy ";

First, let's look at the line of code. It means that if the addresses in the memory are the same, "clone is a shortest copy" is returned ", if the address space in the memory is the same, you can determine whether it is the same object.


3. As explained in the previous document, implements requires the classes of the Cloneable interface to overload Object. clone.

Let's dig a hole here. I will fill it out later for a careful study on Deep copy.

Related Article

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.