[1685790 views]

[]

Odi's astoundingly incomplete notes

New entries | Code

Cloneable does not supersede the copy constructor

Common misconception: "Copy constructors are a relic from the C++ ages. In Java we have the Cloneable interface."

The clone method is handy when one has an object of an unknown (sub)class and you need a copy. You will most likely end up with an object of the same class. Consider the following scenario: You have a business object and you need to "split" it. So you need to copy parts of this structure. Some of the objects will be of a subtype of the declared field. So only their clone method can correctly perform the copy.

The copy constructor is much more type-safe. You know exactly which class you create and its constructor accepts an object of a well-known class. A copy constructor for example allows you do "downcast" an object. Consider the following scenario: You have an object of the last final class in a class hierarchy. Now you have to pass this object on to an XML serialization but you only want fields of a superclass to be serialized. A copy constructor of that superclass will solve the problem.

A variant of the copy constructor is the template pattern. In the template pattern the copy constructor accepts a template object of a superclass to initialize its state.


posted on 2006-06-29 17:55 UTC in Code | 0 comments | permalink