Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Clone method in java?

Tags:

java

clone

copy

I heard that you should avoid it in your code but it was implemented for some reason so is there a case where using it is actually a good (or not bad) choice or should I always try to avoid it?

like image 295
kojkl Avatar asked Oct 26 '14 22:10

kojkl


1 Answers

Josh Bloch answered this perfectly:

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. There are a few design flaws, the biggest of which is that the Cloneable interface does not have a clone method. And that means it simply doesn't work: making something Cloneable doesn't say anything about what you can do with it. Instead, it says something about what it can do internally. It says that if by calling super.clone repeatedly it ends up calling Object's clone method, this method will return a field copy of the original.

But it doesn't say anything about what you can do with an object that implements the Cloneable interface, which means that you can't do a polymorphic clone operation. If I have an array of Cloneable, you would think that I could run down that array and clone every element to make a deep copy of the array, but I can't. You cannot cast something to Cloneable and call the clone method, because Cloneable doesn't have a public clone method and neither does Object. If you try to cast to Cloneable and call the clone method, the compiler will say you are trying to call the protected clone method on object.

It's a shame that Cloneable is broken, but it happens. The original Java APIs were done very quickly under a tight deadline to meet a closing market window. The original Java team did an incredible job, but not all of the APIs are perfect. Cloneable is a weak spot, and I think people should be aware of its limitations.

like image 168
Afforess Avatar answered Sep 20 '22 05:09

Afforess