Object Cloning

suggest change

Remarks

Cloning can be tricky, especially when the object’s fields hold other objects. There are situations where you want to perform a deep copy, instead of only copying the field values (i.e. references to the other objects).

The bottom line is clone is broken, and you should think twice before implementing the Cloneable interface and overriding the clone method. The clone method is declared in the Object class and not in the Cloneable interface, so Cloneable fails to function as an interface because it lacks a public clone method. The result is the contract for using clone is thinly documented and weakly enforced. For example, a class that overrides clone sometimes relies on all its parent classes also overriding clone. They are not enforced to do so, and if they do not your code may throw exceptions.

A much better solution for providing cloning functionality is to provide a copy constructor or copy factory. Refer to Joshua Bloch’s Effective Java Item 11: Override clone judiciously.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Object Cloning:
* Object Cloning

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
73 Object Cloning
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap