Object Clone Shallow copy doesn't change variable

后端 未结 3 1316
生来不讨喜
生来不讨喜 2021-01-15 11:25

I tried to clone an object and change member functions of new clonned object. If it is shallow copy and according to wiki page, shallow copy and original object point to sam

相关标签:
3条回答
  • 2021-01-15 11:49

    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.

    0 讨论(0)
  • 2021-01-15 12:06

    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.

    0 讨论(0)
  • 2021-01-15 12:09

    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?

    0 讨论(0)
提交回复
热议问题