Object Clone Shallow copy doesn't change variable

狂风中的少年 提交于 2019-12-01 13:21:01

When you call object.clone(), new object is created. So as a result you get reference to this object. Object with only primitive type field are cloning perfectly. As a result you get a full independent from your obj1 copy. But if your object has fields with references, you need to do a deep cloning.

surfen

Shallow copy of obj1 creates another instance obj2 of your CloneExample class (obj1!=obj2). They don't share value members.

But if our class contained a reference type, for example java.util.Date, then changing it's value would be reflected in both object if they shared reference to that java.util.Date.

In Java, what is a shallow copy?

why do you think clone is a shallow copy? see here: http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#clone()

As it says - what clone does is implementation dependent. Also a 'shallow copy' doesn't simply create a new reference to the same object - generally it means that a new instance is created with the same internal members as the object copied-from. But if you change a member variable of the new obj to point to something new, you are not changing member vars of original obj.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!