What is wrong with this clone()?

前端 未结 9 2021
梦如初夏
梦如初夏 2020-12-09 23:00

I have written this clone method for when the parent of the Employee class is abstract and the clone() method in the parent class is abstract.I wanted to copy the primitive

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 23:08

    The standard pattern for making a class cloneable is:

    1. Implement Cloneable
    2. Override the clone() method and make it public
    3. In clone() call super.clone() and then copy any mutable object's state

    You should not create a new object using new. The proper way is to call super.clone() for a new instance. Object's clone() is special and will create a new copy of the object and copy its primitive fields and references.

    For example:

    public class Person implements Cloneable {
        protected String name;
        // Note that overridden clone is public
        public Object clone() {
            Person clone = (Person)super.clone();
            // No need to copy name as the reference will be
            // copied by Object's clone and String is immutable
            return clone;
        }
    }
    
    public class Employee extends Person {
        protected int id;
        protected java.awt.Point location;
        public Object clone() {
            Employee  clone = (Employee )super.clone();
            // No need to copy id as Object's clone has already copied it
            // Need to clone location as Point is mutable and could change
            clone.location = location.clone();
            return clone;
        }
    }
    

提交回复
热议问题