-----------Clone () cloning mechanism in the Java object class
Package Java_lang_object;public class User implements cloneable {public Address address;public int age;public String name; Public User (int age,string name) {this.age = Age;this.name = name;this.address = new Address ("Guangzhou Tianhe"); Public User Clone () throws Clonenotsupportedexception{return (user) Super.clone ();}}
Package Java_lang_object;public class Address {public String detail;public address (String detail) {this.detail = detail;}}
package java_lang_object;/** * Cloning class Test (the Clone () of object is just a shallow clone, that is, a variable of reference type is not cloned) * @author administrator *1, implementing cloning to let the class implement the Cloneable interface *2, overriding the Clone () method in the parent class object *3, cloning is just a copy of the cloned object ( Replicas: That is, the content is the same, pointing to the heap memory of the same object, but with different references, allocating two stacks of space) *//* * system-provided Clone () method (that is, the Clone () method provided by the object class) is very efficient , more than our own static clone () efficient */public class clonetest {/* * 1, U1, U2, respectively, are two variables, stored in the stack memory, pointing to the heap memory address is not the same (so U1 == u2 is false) * 2, */public static void main ( String[] args) throws clonenotsupportedexception {user u1 = new user ( 29, "Hubei");//clone gets a copy of the U1 object User u2 = u1.clone ();//Two objects belonging to two different references, unequal System.out.println (u1 ==  U2);//Two a different reference to a different heap memory space, the value of the address instance variable is equal to the clone () mechanism provided by the/* * object class to "simply copy" the instance variables in the object, If the type of the instance variable is a reference-type * object, the clone mechanism simply duplicates the reference variable (which is also why the address instance variable is equal because two address instance variables * Point to the same heap memory)  *  */SYSTEM.OUT.PRIntln (u1.address == u2.address);//instance variables are equal System.out.println (u1.age == u2.age); System.out.println (U1.address.detail == u2.address.detail);//return true}}
This article is from the "11941149" blog, please be sure to keep this source http://11951149.blog.51cto.com/11941149/1851610
-----------Clone () cloning mechanism in the Java object class