Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 847
Posa Avatar asked Apr 03 '13 14:04

Posa


People also ask

Why is clone () method used in Java?

Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.

How many ways we can clone object in Java?

There are two types of object cloning - shallow cloning, and deep cloning. Let's understand each of them and find out the best way to implement cloning in our Java programs.

Why is object clone () method available only to classes that implement cloneable interface?

The clone() method isn't defined by the Cloneable interface. The clone method in the Object class is protected to prevent a client class from calling it - Only subclasses can call or override clone, and doing so is a bad idea.

Which method is used to clone an object in Java?

The clone() method of Object class is used to clone an object. The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create.


1 Answers

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

like image 70
dcernahoschi Avatar answered Sep 21 '22 05:09

dcernahoschi