Object Cloning in java


Javaobjects 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.

By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:

1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.
2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.
Example:
1) you have Employee class with 3 attributes. Id, name and department.
2) you have Department class has two attributes. id and name.
then in main...
Department dept = new Department(1, "Human Resource");
  Employee original = new Employee(1, "Admin", dept);
  //Lets create a clone of original object
  Employee cloned = (Employee) original.clone();

Comments