Brief Introduction to the object cloning feature of Java

Source: Internet
Author: User

In the reflection on the value transfer and extension in Java, we have discussed that all objects extended to the cloning technology in Java are subclasses of the Object class. We know that Java is a pure object-oriented programming language. In Java, the top-level parent classes of all classes are java. lang. object class, that is, if a class does not show a declarative inheritance relationship, its parent class is java by default. lang. object.

There is a very simple way to prove this. Let's write a Test class, as shown below:

Public class Test {public void someMethod () {super. clone () ;}} calls super. clone (). No error is reported during compilation. In fact, the clone () method is a protected method provided by the java. lang. Object Class.

Object cloning
This article describes the Object cloning feature of java by introducing the Java. lang. Object # clone () method.

The java. lang. Object # clone () method is implemented by java. lang. Object, which mainly clones the Object itself.

First, let's look at the following example:

Public class TestClone {public static void main (String [] args) {MyClone myClone1 = new MyClone ("clone1"); MyClone myClone2 = (MyClone) myClone1.clone (); if (myClone2! = Null) {System. out. println (myClone2.getName (); System. out. println ("myClone2 equals myClone1:" + myClone2.equals (myClone1);} else {System. out. println ("Clone Not Supported") ;}} class MyClone {private String name; public MyClone (String name) {this. name = name;} public String getName () {return name;} public void setName (String name) {this. name = name;} public Object clone () {try {return super. clone ();} catch (CloneNotSupportedException e) {return null ;}} compile and execute TestClone, print out:

C: clone> javac *. java C: clone> java TestClone Clone Not Supported C: clone> description MyClone # clone () method calls super. cloneNotSupportedException is thrown during clone (). cloning is not supported.

Why can't I call the clone () method provided in the parent class java. lang. Object?

It turns out that Java provides this method, but considering security issues, on the one hand, it sets the clone () access level to the protected type to restrict external class access;

On the other hand, it is mandatory to provide the clone function subclass to implement java. lang. the Cloneable interface. during runtime, JVM checks the class that calls the clone () method. If this class does not implement java. lang. the Cloneable interface throws a CloneNotSupportedException exception.

The java. lang. Cloneable interface is an empty interface without declaring any attributes and methods. This interface only tells JVM that the "clone" function must be enabled for the Implementation class of this interface.

The MyClone class is slightly changed to implement the Cloneable interface:

Class MyClone implements Cloneable {... // others do not change} compile and execute TestClone, print: C: clone> javac *. java C: clone> java TestClone clone1 myClone2 equals myClone1: false C: clone> Based on the results, we can find:

1. myClone1.clone () cloned the object with the same attribute value as myClone1.

2, but the cloned object myClone2 and myClone1 are not the same object (with different memory space)

Summary
If you want A class A to provide the cloning function, the class must implement the java. lang. Cloneable interface and reload the java. lang. Object # clone () method.

Public class A extends Cloneable {public Object clone () {try {return super. clone ();} catch (CloneNotSupportedException e) {// throw (new InternalError (e. getMessage (); return null ;}} in-depth object cloning
The preceding example shows how to clone an object with simple attributes (String, int, boolean, etc.

However, if an object's attribute type is List, Map, or other user-defined classes, how does the clone behavior work?

Most of the time, we hope that even if the attribute value of the cloned object is modified, it will not affect the original object. This kind of clone is called the deep-level clone of the object. How can we achieve deep object cloning?

Verify the object cloning method
To verify the object cloning method, we have improved the above example as follows (to save space, we have omitted the setter and getter methods ):

Public class TestClone {public static void main (String [] args) {// set the value MyClone myClone1 = new MyClone ("clone1") for the cloned object; myClone1.setBoolValue (true ); myClone1.setIntValue (100); // set the List Value List <Element> listValue = new ArrayList <Element> (); listValue. add (new Element ("ListElement1"); listValue. add (new Element ("ListElement2"); listValue. add (new Element ("ListElement3"); myClone1.setListValue (listValue); // Set the Element value Element element1 = new Element ("element1"); myClone1.setElement (element1); // clone MyClone myClone2 = (MyClone) myClone1.clone (); if (myClone2! = Null ){

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.