How does java clone() really use shallow copy?

Giorgi Lagidze :

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.

FunctionR :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=104035&siteId=1