I read one paragraph from the Internet regarding cloning. But I didn\'t quite get it, so can someone explain it clearly?
If the class has final fields, th
o.clone()
calls Object.clone()
, which makes a memory copy of o
. Thereafter the copied references cannot be changed for final field, so we have involuntary aliasing;o
changes, the clone involuntarily changes, too;I believe the article is talking about clone()
via clone-chaining (via super.clone()
), such that eventually Object.clone()
is called, which makes a flat memory copy of the object being cloned via native code.
Let's say we have the following example (from the blog post mentioned below):
public class Person implements Cloneable
{
private final Brain brain; // brain is final since I do not want
// any transplant on it once created!
// ...
}
and
person2 = (Person) person1.clone();
then person2 has the same memory-part for the field brain as person1, i.e. both hold the same reference to the same brain. Then since Person objects are mutable, they can learn things:
person1.learn(dvorakTyping);
then magically person2 can type on a dvorak keyboard as well. With immutable objects, this problem doesn't occur (though cloning's still problematic since final fields can still not be initialized via parameters, as in constructors).
The reason for my very first half sentence: You can implement clone via calling one of the object's constructors. Some people claim this is against clone's contracts, but it isn't. Here's a good blog post about why to call a constructor within clone (one main reason being those final fields).
Reading Hemal's comment on mre's answer, I did glance over the blog post the question cited, and it turns out, the post copied some sentences from the blog post I cited, but without the very good code examples. LOL.