Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does java clone() really use shallow copy?

Tags:

java

clone

I know It might be already asked, but my question is something different. I've searched and I know java method object.clone() uses shallow copy which means copying references and not the actual objects. Let's say I have a dog Class

 Class Dog{
     public Dog(String name, DogTail tail, DogEar ear){
          this.name = name;
          this.tail = tail;
          this.ear  = ear;   
     } 
} 
DogTail t = new DogTail(); 
DogEar ear = new DogEar(); 
Dog dog1 = new Dog("good", t,ear);

let's say I want to get a copy of dog1.

Dog dognew = dog1.clone();

If this clone() method uses shallow copy, it means copying references. So If I change t object created above or ear method, it's gonna change in the dognew object or vice versa. How is this cloning good? This question was born because someone said that creating an big huge object is worse than cloning, as you save performance while using clone() method.

like image 974
Chemistry Avatar asked Aug 06 '26 09:08

Chemistry


2 Answers

The default version of clone() method creates the shallow copy of an object.

The shallow copy of an object will have exact copy of all the fields of original object. If original object has any references to other objects as fields, then only references of those objects are copied into clone object, copy of those objects are not created. That means any changes made to those objects through clone object will be reflected in original object or vice-versa.

To create a deep copy of an object, you could override the clone() method.

protected Object clone() throws CloneNotSupportedException
{
    DogTail tail = (DogTail) this.tail.clone();

    Dog dog = (Dog) super.clone();

    dog.tail = tail;

    return dog;
}
like image 174
apxcode Avatar answered Aug 07 '26 22:08

apxcode


"So If I change t object created above or ear method, it's gonna change in the dognew object or vice versa."

It depends on what you mean by "change":

If you mean change the state of the DogTail instance that t references, e.g. t.setSomething(someValue);, then yes. It's the same instance, doesn't matter who causes a change or where the change happens.

If however you mean change what t in the clone references, e.g. t = new DogTail();, t in the original will not be affected. The t in the clone and the original will reference different instances after that.

like image 42
Max Vollmer Avatar answered Aug 07 '26 23:08

Max Vollmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!