I was looking for tutorials online about java cloning, but only found the disadvantages to clone() and nothing about the advantages. I would like to know some of the advantages of using Java clone().
Cloning has its uses certainly. Imagine any kind of a business application where you have records of data, represented in objects, that you can "save as" (duplicate and rename). If that data is held in a object that implements the Cloneable interface then you can clone the original and update it with the new information.
This is superior to creating a new object instance and copying all of the data over explicitly. Some people address this with helper classes and methods which do the copying, but then you have the information required to copy a class outside of the class itself which is poor OO programming.
Another use case I like is when I use a class to as a backing store for a GUI and that GUI has a reset button. When the GUI is initialized, I clone the backing store object. Then if the user presses restore, I just reinitialize the GUI to the values in the clone object, rather than figure what information they might have changed or get a new copy of the original information from storage. There are many uses, certainly.
But as you know cloning can raise issues in an inheritance framework and clutters up otherwise lightweight data classes, so I wouldn't make an object cloneable unless there was a business requirement for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With