Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the need of cloning a object in Java

Tags:

java

clone

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.

like image 731
Anand Avatar asked Apr 08 '12 18:04

Anand


People also ask

Why do we need to clone objects in Java?

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.

What does clone method do in Java?

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.

What is cloning in Java & types of cloning in Java?

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.

What is the purpose of the following code protected object clone () throws CloneNotSupportedException?

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.


1 Answers

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.

like image 163
DOK Avatar answered Sep 21 '22 14:09

DOK