| Start |
|---|
| Cloning performing a deep copy To copy nested objects, a deep copy (opens new window) must be performed, as shown in this example. |
| Cloning using a copy constructor An easy way to clone an object is by implementing a copy constructor. |
| Cloning by implementing Clonable interface Cloning an object by implementing the Cloneable (opens new window) interface. |
| Cloning performing a shallow copy Default behavior when cloning an object is to perform a shallow copy (opens new window) of the object's fields. In that case, both the original object and the cloned object, hold references to the same objects. This example shows that behavior. |
Cloning using a copy factory RemarksCloning can be tricky, especially when the object's fields hold other objects. There are situations where you want to perform a deep copy (opens new window), instead of only copying the field values (i.e. references to the other objects). The bottom line is clone is broken (opens new window), and you should think twice before implementing the A much better solution for providing cloning functionality is to provide a copy constructor or copy factory. Refer to Joshua Bloch's Effective Java (opens new window) Item 11: Override clone judiciously. |
Read Article
https://develop.horje.com/learn/1434/reference