Clonable is an interface that serves as a marker, indicating that a class is eligible for object cloning. Object cloning refers to the process of creating a duplicate, or clone, of an object. Cloning can be a valuable tool for making copies of objects when you want to preserve the state of an existing object without affecting it.
To make a class clonable, you need to do the following:
- Implement the
- Override the
clonemethod from the
Shallow vs. Deep Cloning
When you implement cloning, you should be aware of the difference between shallow and deep cloning:
- Shallow Cloning: This copies the object and its non-primitive fields. However, if the object contains references to other objects, those references in the clone still point to the same objects as in the original. In other words, the clone shares references to objects within the original.
- Deep Cloning: This creates a new object along with copies of all the objects referenced by the original object. The entire object tree is duplicated. Achieving deep cloning can be more complex and may require custom implementations.
To achieve deep cloning, you need to manually copy all referenced objects, creating new instances for each of them, and so on, recursively.