Search code examples
javaclone

what is the need of cloning a object in Java


I was reading about the cloning in Java, how to make shallow/deep copies of object etc.

I was wondering why do I need to create object clones in Java? Any real time examples could be helpful in understanding.


Solution

  • Quite often you want to use immutable objects, in which case cloning is an essential part of your code. If for example you have an immutable object that has a list or array type field, your getter should always return a clone of the list or array to preserve immutability.

    The other typical use case is when you want "transactional" modifications, when you call several state changing methods but only want the result to be visible if all of them are successful.