Figure 3. After a deep copy of obj1
If either of these contained objects themselves contain objects, then,in a deep copy, those objects are copied as well, and so on until theentire graph is traversed and copied.Each object is responsible for cloning itself via its
method, inherited from
, makes a shallow copy of the object. To achieve a deep copy, extra logic must be added thatexplicitly calls all contained objects'
methods, which in turn calltheir contained objects'
methods, and so on. Getting thiscorrect can be difficult and time consuming, and is rarely fun. To makethings even more complicated, if an object can't be modified directlyand its
method produces a shallow copy, then the class mustbe extended, the
method overridden, and this new class usedin place of the old. (For example,
does not contain the logicnecessary for a deep copy.) And if you want to write code that defersuntil runtime the question of whether to make a deep or shallow copyan object, you're in for an even more complicated situation. In thiscase, there must be two copy functions for each object: one for a deepcopy and one for a shallow. Finally, even if the object being deepcopied contains multiple references to another object, the latter objectshould still only be copied once. This prevents the proliferation of objects, and heads off the special situation in which a circularreference produces an infinite loop of copies.
Back in January of 1998,
column byMark Johnson with an article on serialization, "Do it the 'Nescafé' way-- with freeze-dried JavaBeans." To summarize, serialization is theability to turn a graph of objects (including the degenerate case of asingle object) into an array of bytes that can be turned back into an