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

前端 未结 4 1356
面向向阳花
面向向阳花 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:59

    Let's look at a section from your example: obj.id = new Integer(4);. Here you're not changing the internal representation of id - you're assigning new instance to the id reference. Both Integer and String are immutable so it's hard to feel the difference of shallow vs deep copy with them. Try to add e.g. an ArrayList attribute and in order to modify it you can e.g. add a new element obj.myList.add(13);

提交回复
热议问题