Chemistry
Chemistry

Reputation: 171

How does java clone() really use shallow copy?

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.

Upvotes: 3

Views: 101

Answers (2)

Max Vollmer
Max Vollmer

Reputation: 8598

"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.

Upvotes: 1

axwcode
axwcode

Reputation: 7824

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;
}

Upvotes: 1

Related Questions