I think clone()
could maybe used with your own, well defined, final
data structure (or record) that is not exactly a class (has all public
fields and no methods). Also, these fields should be either primitive data types, or immutable types (like String
s) so could be shared without problems.
Cloning such a structure by assigning all fields manually simply means more code, makes the maintenance more difficult (more changes after you add or remove a field) and I really do not understand what exactly benefits this brings.
C / C++ has an assignment statement for the structures to copy all fields in one go and in some cases does this transparently ("structure passed by value"). Java could use clone for the similar goal. After all, simply assigning a double
value to a variable is a kind of cloning: all fields of the IEEE data structure (sign bit, exponent, fraction) are copied. Never used to be any fundamental problems with this. How this is different from cloning a final Point
class with two public integer fields, x
and y
?
Most of arguments against clone()
are valid for cases when the exact class of the instance in use is not known or it may be unknown invisible fields that may not get initialized correctly.