7
votes

In Java, to make a class cloneable, we need to implement Cloneable interface. Implementing this interface, is just to say that this class supports cloning.

But what is the motive of Java language designers for not making "allowed-to-clone" as default functionality of each class?

We have default implementation for shallow copy already present. Then why this restriction ?

4

4 Answers

5
votes

Think about cloning an object with nested properties. How deep recursively do you want to go? This could be tough for the memory, so the developers left it for us to decide.

4
votes

It's a marker interface to let Java know that implementing class is intentionally being designed for cloning(similar use as of other marker interfaces). If you read further, then you find below:

By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.

You need to provide custom method for cloning. By having the interface Cloneable, Java is aware that you are intentionally supporting cloning of your object. By providing your custom clone method, you are over-ridding the default clone method of the object.

This way, you get the flexibility to decide(Mark), which objects can be cloned and which not. If clone-able then up to what level(very useful in object graph cases).

0
votes

Many reasons stand in the way, the chief one being that cloning is not a problem solvable for the general case, much like serialization.

The shallow copy you get by default will in many cases destroy the object's invariants so it is out of the picture as a general, default cloning mechanism.

0
votes

The "Cloneable" interface is part of a design pattern called a "Marker Class". Basically, within the clone method will be some reference to a type "Cloneable". When you implement the cloneable interface, it means that your class can be referenced as type "Cloneable".

The other reason, in practicality, is that you override the "clone()" method, and clone in your own specific way. That means the data that you deem important is present in the new class.