The clone()
method and Cloneable
interface, suggested by other authors here, were created with the incorrect assumption that it would be a good idea to have a generic copying method. The default implementations does a shallow clone of the current object, but you could override it to do a deep clone.
There is no correct, generic way to copy arbitrary objects, what you want to copy depends on the objects involved. For example, immutable objects never need copying (that'd just be a waste of space), while some types of objects can't be copied (how would you copy a FileOutputStream
, for example?).
The way I find most elegant is immutable objects with methods that return a copy with just one field changed:
class Pony {
private final String name;
private final Color color;
private final int tailLength;
// constructors and accessors omitted
Pony withName(String newName) {
return new Pony(newName, color, tailLength);
}
Pony withColor(Color newColor) {
return new Pony(name, newColor, tailLength);
}
Pony withTailLength(String newTailLength) {
return new Pony(name, color, newTailLength);
}
}
// Usage:
Pony tony = new Pony("Tony", Color.DAPPLE, 32);
Pony maurice = tony.withName("Maurice") // Maurice is like Tony, but black.
.withColor(Color.BLACK);
Unfortunately, you get a lot of boilerplate this way, and there's no mainstream IDE support either (there may be plugins, though). Related to this is the Builder pattern recommended by Josh Bloch in Effective Java.