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.
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing time to be performed that is why we use object cloning.
clone() method in Java Object class has a clone method which can be used to copy the values of an object without any side-effect. Assignment operator has a side-effect that when a reference is assigned to another reference then a new object is not created and both the reference point to the same object.
Object cloning in Java is the process of creating an exact copy of the original object. In other words, it is a way of creating a new object by copying all the data and attributes from the original object. This is only possible by implementing clone() method of the java. lang. Object class.
Class CloneNotSupportedException Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.
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.
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