Object class clone method

Object of the clone () method is protected and is shallow copy, want to use the clone method to override it, only to realize the implements Cloneable can call this method, otherwise it will throw an exception CloneNotSupportedException.

@Override
     public Object clone () { 
        Object O = null ;
         the try { 
            O = Super .clone (); 
        } the catch (CloneNotSupportedException E) { 
            e.printStackTrace (); 
        } 
//         the Person P = (the Person) O;
 //         P .book = (Book) p.getBook () clone ();. // release these two is the use of a deep copy of the 
        return O; 
    }

When we need to copy objects commonly used in three ways

public static void main(String[] args){
Book b = new Book("java");
Person p = new Person("wt",b);
Person p1 = new Person(p);
Person p2 = (Person) p.clone();
b.setBookName("js");
p.setName("zjj");
System.out.println("P:"+p);
System.out.println("P1:"+p1);
System.out.println("P2:"+p2);
}

When using a shallow copy clone (i.e., not releasing the two paragraphs), the only copy of the object does not contain a copy of the object referenced object:

P: {name: ZJJ, Book: bookName {:}} JS             
Pl: {name: wt, Book: {bookName: JS}}       // either p1 or p2, the value is a direct copy of the basic types of values, but the reference the object type is a copy of the address 
P2: {name: wt, Book: {bookName: JS}}       // so that once an object reference to the original value of p is changed, the target would change shallow copy
 

When using a deep copy clone (i.e. release that two segments):

P2: {name: wt, Book: {bookName: Java}}       // when deep copy, even for objects in the object is a copy of the value, the original value of the reference object changes will not affect its

 

Guess you like

Origin www.cnblogs.com/sycamore0802/p/11247877.html