Object Cloning


Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this 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.
There are two types of object cloning – shallow cloning, and deep cloning. Let's understand each of them and find out the best way to implement cloning in our Java programs.
clone() method saves the extra processing task for creating the exact copy of an object. As you can see in the below example, both reference variables have the same value. If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object.
Clone() Method
This method belongs to the Object class, which is a base class of every class created in Java. This method helps to create a copy of the object, but if the class doesn't support a cloneable interface then it leads to the exception, " CloneNotSupportedException"
clone() is a method in the Java programming language for object duplication. In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality
Posted on by