Search code examples
javaclonedeep-copycloneable

Is the Java clone() method the only way to achieve polymorphic cloning?


I need to equip my class with polymorphic cloning (deep copy), i.e. I need something like this to work:

SuperType original = new SubType();
SuperType copy = original.clone();

where original.clone() can be substituted by any mechanism to create a deep copy, and the actual type of copy shall be SubType, because original is also a SubType.

Is the clone() method and Cloneable interface the only way to achieve this? Factory methods and copy constructors cannot by used, since the actual class is known only in run time, right? Are there any other suggested methods except those serialize-deserialize approaches, and the Java deep-cloning library which is IMHO even worse black magic than the clone() method?

Thanks, Petr


Solution

  • Actually Object's clone() method is not allowing you to do any polymorphic calling because is protected. Implementing Cloneable is of no use either because it doesn't contain a clone() method.

    You can do polymorphic cloning by providing a polymorphic method for the cloned classes that in turn invoke the copy constructor.

    abstract class SuperType {
        public SuperType(SuperType t) {
        }
    
        public abstract SuperType deepCopy();
    }
    
    class SomeType extends SuperType {
    
        SomeType(SomeType t) {
            //copy constructor
        }
    
        @Override
        public SomeType deepCopy() {                        
            return new SomeType(this);
        }
    }
    
     ...
    
    SuperType original = new SubType();
    SuperType copy = original.deepCopy(); //the deepCopy is called on children classes
    

    See also:

    Joshua Block's opinion on cloning vs. copy constructor