Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of Java Cloning

Tags:

java

cloneable

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().

like image 493
user2273278 Avatar asked May 02 '13 01:05

user2273278


1 Answers

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.

like image 106
CBass Avatar answered Sep 30 '22 10:09

CBass