If either of these is unneeded, a reference to the original data is sufficient and more efficient, as no copying occurs.
The design goal of most objects is to give the resemblance of being made out of one monolithic block even though most are not.
In these cases a custom implementation of copying is generally required; this issue and solution dates to Smalltalk-80.
When the program wants to modify an object, it can determine if the data is shared (by examining the counter) and can do a deep copy if needed.
Objects are never created implicitly but instead are always passed or assigned by a reference variable.
)[11] The Java Virtual Machine manages garbage collection so that objects are cleaned up after they are no longer reachable.
If this method is used, the class must implement the Cloneable marker interface, or else it will throw a "Clone Not Supported Exception".
After obtaining a copy from the parent class, a class' own clone() method may then provide custom cloning capability, like deep copying (i.e. duplicate some of the structures referred to by the object) or giving the new instance a new unique ID.
Most interfaces and abstract classes in Java do not specify a public clone() method.
Thus, often the only way to use the clone() method is if the class of an object is known, which is contrary to the abstraction principle of using the most generic type possible.
This is typically used for persistence and wire protocol purposes, but it does create copies of objects and, unlike clone, a deep copy that gracefully handles cycled graphs of objects is readily available with minimal effort from a programmer.
Both of these methods suffer from a notable problem: the constructor is not used for objects copied with clone or serialization.
This can lead to bugs with improperly initialized data, prevents the use of final member fields, and makes maintenance challenging.
Some utilities attempt to overcome these issues by using reflection to deep copy objects, such as the deep-cloning library.
The Eiffel class ANY contains features for shallow and deep copying and cloning of objects.
In C#, rather than using the interface ICloneable, a generic extension method can be used to create a deep copy using reflection.
[13] Programmers may define special methods __copy__() and __deepcopy__() in an object to provide custom copying implementation.
In Ruby, all objects inherit two methods for performing shallow copies, clone and dup.
Deep copies may be achieved by dumping and loading an object's byte stream or YAML serialization.