clone() method in Java

前端 未结 5 1114
再見小時候
再見小時候 2021-02-14 22:14

as I understood, the method clone() gives us the ability to copy object (no refernce) in Java. But I also read, that the copy is shallow. So what the point? Which a

5条回答
  •  天命终不由人
    2021-02-14 23:08

    An assignment copies the reference of an instance to a variable. A clone operation will clone the instance (and assign a reference to the clone).

    With assignment, you'll end up with multiple variables pointing to one object, with cloning you'll have multiple variables that hold references of multiple objects.

    SomeCloneable a = new SomeCloneable();
    SomeCloneable b = a;                     // a and b point to the same object
    
    /* versus */
    
    SomeCloneable a = new SomeCloneable();
    SomeCloneable b = a.clone();             // a and b point to the different objects
    

提交回复
热议问题