Cloning in Java

前端 未结 4 1718
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 07:18

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

4条回答
  •  旧巷少年郎
    2021-02-04 07:31

    In short

    • 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;
    • the unwanted aliasing and mutability do not go well with each other: If o changes, the clone involuntarily changes, too;
    • the statements in the blog post you cite are copied from this much better blog post, which attests the statements with good code examples.

    Details and examples about cloning via `Object.clone()'

    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).

    Cloning via constructor calls

    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).


    Update

    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.

提交回复
热议问题