Why classes in Java are not cloned by default

In Java, to make a class cloned, we need to implement the Cloneable interface. The implementation of this interface is to say that this class supports cloning.

But what is the motive of Java developers to make the "allowed clone" the standard functionality of each class?

We have a default implementation for an already inactive copy. Then why is this a limitation?

+7
source share
4 answers

Consider cloning an object with nested properties. How deep do you want to go recursively? It can be hard for memory, so the developers left it for us to decide.

+5
source

This is a token interface that allows Java to know that the implementing class is intentionally intended for cloning (similar use with other token interfaces). If you read further, you will find below:

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

You need to provide a custom cloning method. With the Cloneable interface, Java knows that you intentionally support the cloning of your object. By providing your own clone method, you override 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 to clone, then to what level (very useful in the case of object graphs).

+3
source

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

The shallow copy that you get by default will in many cases destroy the invariants of the object, so it will not appear as a general clone mechanism by default.

0
source

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

Another reason for practicality is that you override the clone () method and clone in your own way. This means that the data that you consider important is present in the new class.

0
source

All Articles