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.
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.
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.
Having a cloned copy of something means you can have "before" and "after" versions. You can leave the original alone while you test something out with a copy. You can provide undo by simply reverting to the original version.
A concrete example of cloning is the: prototype design pattern
As Cloning itself says Duplicate copy of something, so In java when we say cloning of object it means to create or have another same object of existing one.
When we do cloning? when we saw that the creating new object every time is time consuming or we need new object having same or little bit difference w.r.t all ready created object, then we use cloning.
Cloning are of 3 types in java
Shallow copy
Shallow copy is the process in which the state of the object is copied to another object, but both the objects point to the same reference in heap area.
Deep Copy
In Deep Copy, two separate objects are created and in deep copy. In this each field of one object is copied to another object.
Now third category to overcome this difficulty in java is the concept of cloning.
Cloning in java is done by implements Cloneable interface. Cloneable is marker interface.
For more deep knowledge on cloning Refer : Cloning in java
You may use a deep cloned copy of your object because you may need a partial result in some method which you would like to use later.
As a way to help preserve encasulation (and therefore make you code more robust), you could clone objects before returnng them from a getter. For example, a getDate method might clone a date field before returning to the caller.