Java cloneable document translation and instance full parsing

Source: Internet
Author: User
Tags shallow copy

Title:java.lang.Cloneable parsing date:2014-12-05 14:26:01

Tags:java

Java.lang Interface cloneable

All known subinterfaces: All known sub-interfaces

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's legal for this method to make a field-for-field copy of

Instances of that class.


Invoking Object ' s Clone method on a instance that does not implement the

Cloneable interface results in the exception clonenotsupportedexception being

Thrown.


By convention, classes it implement this interface should override Object.clone

(which is protected) and 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 a object merely by virtue of the fact that it implements this

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

Guarantee that it'll succeed.

This class implements the Cloneable interface to indicate that the Object.clone () method can replicate instances of the class in a legal manner.

If an instance of the Clone method method is called without the implements Cloneable interface, the Clonenotsupportedexception Exception is thrown.

By habit, the classes that implements the Cloneable interface needs to be overloaded object.clone (it is protected).

Note that this interface does not contain the Clone method. Therefore, it is impossible for an object to implement it on clone. Even if reflection calls the Clone method, it does not guarantee that the call will succeed.

since:jdk1.0 See Also:clonenotsupportedexception, Object.clone ()


The above direct translation from Java doc, it must have been very clear. Next, a simple example of the technical transformation, to record a bit.

/**

* 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);

}


/**

* References to replicated tests

*/


public static void Referencetest () {

person person = new person ();


Person.setid (1);

Person.setname ("Wenyue");


person copy = person;


if (copy.equals (person))

System.out.println ("Refer to copied person and copy is the same object");

Else

SYSTEM.OUT.PRINTLN ("Reference to copied person and copy is not the same object");


SYSTEM.OUT.PRINTLN (person);

SYSTEM.OUT.PRINTLN (copy);

System.out.println (Person.getname ());

System.out.println (Copy.getname ());


}


/**

* For the test method of the clone of object, and to detect that clone implements a shallow 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 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 Copy */

Referencetest ();


}



}

Give the execution result of the main function:


OK, now let's explain this test code.

You can see that the main function performs two test methods, Clonetest () and Referencetest (); The first one implements the test of clone () method for object after Cloneable interface , and the reason for adding a second method is to have a shallow copy of the object, that is, clone (the copy of the default object in Java is a shallow copy). , which is easy to understand by comparing with the copied reference.

1. From the execution results of this code, it can be clearly seen that the clone implementation of copy created a new object (in memory address is different), and reference copy, but the original object's address is copied to the new object, so straight line, Person and copy point to the same address space.

About clone default is a shallow copy of the explanation

2. First, because the ID is the basic data type, then there is no doubt about its copy, directly a 4-byte integer value copied over the line. But name is a string type, and name is just a reference, pointing to a true string object, the reason that clone defaults to a shallow copy is that At clone, the Clone method simply copies the reference value of the string object to the Name field of the new copy object, rather than recreating a string object in memory and pointing a reference to the Name field of the Copy object. The proof is as follows:


String result = Person.getname () ==copy.getname ()? " Clone is a shallow copy ":" Clone is a deep copy ";

First of all, please look at the line code, probably means that if the two addresses in memory are the same, then return "clone is a shallow copy", and the memory of the address space is the same can be judged whether it is the same object.


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

Dig a hole here, and I'll fill it out after a careful study of the deep copy.

Java cloneable document translation and instance full parsing

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.