Search code examples
javac++clonecloneable

Purpose of cloning in Java


I was going through the "special" features of Java, and started reading up on Cloning.

So currently what I understand is Cloning can be used to get a identical copy of an object. To do this you implement the Cloneable interface and override the clone method of Object(Which is really weird IMO)

My questions is more towards the comparison between C++ and Java. Why exactly is a separate clone method required when we already have support for copy constructors. Was there a historical reason on why cloning was thought of as must have feature?

PS: I am not asking about the need to "clone" as in what is the need of cloning a object in Java, what I am asking is the need for Cloneable and the clone method, when Java already supports copy constructors.


Solution

  • IMO you question has two parts.

    What is the need for the Cloneable interface?

    The Cloneable interface is also known as a marker interface, which means that it does not have any methods, its whole purpose is to tell you, the user of that class, that it implements the clone() method which is inherited from Object. This enables you to do a check before calling the clone() method:

    Animal a = new Dog();
    Animal b;
    if (a instanceof Cloneable)
        b = a.clone();
    

    This happens pretty often in Java; see for example the Serializable interface.

    Why does Java need a clone() method at all, as it already has copy constructors?

    The very short answer is polymorphism. How would you correctly clone a Dog instance, through a reference to an Animal, its super class, if you didn't have the clone() method?