Why is the Object class's clone() method giving a deep copy of object?

前端 未结 4 1366
面向向阳花
面向向阳花 2021-01-22 10:25

As per the JAVA documentation, the super.clone() when called returns a shallow copy of the object. In the code below I have two objects name and id

4条回答
  •  暖寄归人
    2021-01-22 10:43

    The name and id fields are references to objects of type String and Integer. When you make a shallow copy the new copy points to the same objects for name and id.

    Then when you do

    obj.name = "Annu_modified";

    You change obj.name to refer to a new object of type String while obj1.name continues to refer to the old object. If you could have changed the object obj.name referred to it would have changed for both. However with a String you can't cause it is a so called immutable object.

提交回复
热议问题