Cloning in Java

前端 未结 4 1716
佛祖请我去吃肉
佛祖请我去吃肉 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:38

    There isn't any problem in cloning final fields it works as for others but not effecitively all the time.

    Sometime it becomes problem for mutable objects

    When we use clone by default it gives shallow copy ( reference to same Object ) , so while overriding clone we try to deep copy all mutable objects.When we try to deep copy final fields problem occurs as final reference ( of final field ) can not be reassigned to new Object.

    public class Person implements Cloneable
    {
        private final Brain brain; 
        private int age;
        public Person(Brain aBrain, int theAge)
        {
            brain = aBrain; 
            age = theAge;
        }
        public Object clone()
        {
            try
            {
                Person another = (Person) super.clone();
                // shallow copy made so far. Now we will make it deep
    
                another.brain = (Brain) brain.clone();
    
    //ERROR: you can't set another.brain 
    
                return another;
            }
            catch(CloneNotSupportedException e) {} 
            //This exception will not occur
        }
    
    }
    

    This example is from the same blog mentioned in another answer by Davefar

提交回复
热议问题