Assume that original
is the name of original CloneTest object, and cloned
is the cloned object that you created from original
using the clone()
method.
This is what happened:
1. Your cloned.name
and original.name
are pointing at the same object, which in this case was a String.
2. Then you asked your original.name
to point to a different String object ("Dolly"). This happens when you assign the new String object ("Dolly") to the reference original.name
.
3. But, the cloned.name
still points to the first String object ("Dolly").
Hence, cloned.name
still prints the 1st String object.
Now, if you are able to change the content of the String object without reassigning the references, then the change in clone.name
will reflect in original.name
. But for String objects, this is not possible due to the immutability of Strings. However, you can reflect the change from the clone
to original
with StringBuffers which are mutable strings so to speak. Take a look at this example code for the same: https://gist.github.com/VijayKrishna/5967668