Sunday, November 13, 2022

Clone() method in Java

 Deep Copy vs Shallow Copy

  • Shallow copy is the method of copying an object and is followed by default in cloning. In this method, the fields of an old object X are copied to the new object Y. While copying the object type field the reference is copied to Y i.e object Y will point to the same location as pointed out by X. If the field value is a primitive type it copies the value of the primitive type.
  • Therefore, any changes made in referenced objects in object X or Y will be reflected in other objects.

Shallow copies are cheap and simple to make. In the above example, we created a shallow copy of the object.

Usage of clone() method – Deep Copy 

  • If we want to create a deep copy of object X and place it in a new object Y then a new copy of any referenced objects fields are created and these references are placed in object Y. This means any changes made in referenced object fields in object X or Y will be reflected only in that object and not in the other. In the below example, we create a deep copy of the object.
  • A deep copy copies all fields and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
// Example 1
class CloneObject implements Cloneable {
// declare variables
String name;
public static void main ( String[] args ) {
// create an object of Main class
CloneObject obj1 = new CloneObject();
// initialize name and version using obj1
obj1.name = "Ram";
// print variable
System.out.println(obj1.name); // Ram
try {
// create a clone of obj1
CloneObject obj2 = (CloneObject) obj1.clone();
// print the variables using obj2
System.out.println(obj2.name); // Ram
} catch (Exception e) {
System.out.println(e);
}
}
}

// Example 2
package Unit4;

class Student implements Cloneable {
int id;
String name;
public Student ( int id, String name ) {
this.id = id;
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class CloneStudent {
public static void main ( String[] args ) {
Student stuObj1 = new Student(3213, "Ram");
Student stuObj2 = null;
try {
//Explicitly Type conversion is req
stuObj2 = (Student) stuObj1.clone();
System.out.println(stuObj2.id);
System.out.println(stuObj2.name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}



No comments:

Post a Comment

techguruspeaks

  Core Java programming Introduction to Java Java Features Writing a Simple Java Program Java Keywords and Comments Variables, Identifiers &...