How to properly override clone method?
The way your code works is pretty close to the "canonical" way to write it. I'd throw an AssertionError
within the catch, though. It signals that that line should never be reached.
catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
Sometimes it's more simple to implement a copy constructor:
public MyObject (MyObject toClone) {
}
It saves you the trouble of handling CloneNotSupportedException
, works with final
fields and you don't have to worry about the type to return.
Do you absolutely have to use clone
? Most people agree that Java's clone
is broken.
Josh Bloch on Design - Copy Constructor versus Cloning
If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think
clone
is deeply broken. [...] It's a shame thatCloneable
is broken, but it happens.
You may read more discussion on the topic in his book Effective Java 2nd Edition, Item 11: Override clone
judiciously. He recommends instead to use a copy constructor or copy factory.
He went on to write pages of pages on how, if you feel you must, you should implement clone
. But he closed with this:
Is all this complexities really necessary? Rarely. If you extend a class that implements
Cloneable
, you have little choice but to implement a well-behavedclone
method. Otherwise, you are better off providing alternative means of object copying, or simply not providing the capability.
The emphasis was his, not mine.
Since you made it clear that you have little choice but to implement clone
, here's what you can do in this case: make sure that MyObject extends java.lang.Object implements java.lang.Cloneable
. If that's the case, then you can guarantee that you will NEVER catch a CloneNotSupportedException
. Throwing AssertionError
as some have suggested seems reasonable, but you can also add a comment that explains why the catch block will never be entered in this particular case.
Alternatively, as others have also suggested, you can perhaps implement clone
without calling super.clone
.