Object cloning in Java refers to the method of creating an object from an existing object, resulting in a replica (or copy).
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".
The syntax for the clone method is:
.
We don’t need to write repetitive codes. The clone() method will perform the same task while writing far fewer lines of code.
Clone() helps to copy an array quickly.
Cloning is the most efficient/easiest way for copying objects.
The method clone() is protected, which is defined in Object class. So, we will have to define our own method.
The clone() method doesn’t call any constructor so there will be no control on object creation.
We need to implement the clone() method in a class whose object has to be cloned, we also need to handle CloneNotSupportedException and calling of the clone() method.
In Java the default cloning is “field by field copy”.
So when JVM is called to perform object cloning there will be two cases:
If the source object has the primitive data members, then a new object will be created with different references and will be returned.
If our source object has member objects of other classes, then only the object references will be copied to the new object because the object class, which is the base class of every class, will not have the idea of class structure of the member object.
We can create a copy of an object using copy constructor and object cloning.
A copy constructor is a special constructor which can create a new object of a class from an already existing object of the same class.
Code for Copy Constructor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Student {
private int id;
private String name;
Student() { //default Constructor
}
//Parameterised Constructor
Student(int idNo, String sName) {
id = idNo;
name = sName;
}
//copy constructor
Student(Student student) {
id = student.id;
name = student.name;
}
}
When we create a shallow copy, object and all the primitive variable and object references will also get copied, but if there are some object references then the same would be copied to a new object. No new copy of reference object will be created. It is generally faster than deep copy as no reference object contained by the source object will be copied. Any change made to references contained by the target object will get reflected in references that are contained by the source object. It is the default cloning method.
Java Implementation of Shallow Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.*;
import java.lang.*;
import java.io.*;
/* Two Points to Remember
1. Class must implement clone() method whose clone object has to be created.
2. The class whose clone object is to be created must implement java.lang.Cloneable interface otherwise it will throw the CloneNotSupportedException when we call clone() method.
*/
class Subject {
String list[] = new String[4];
public Subject(String optionalSubject) {
//Default
list[0] = "Physics";
list[1] = "Chemistry";
list[2] = "Maths";
list[3] = optionalSubject;
}
}
class Student implements Cloneable {
int id;
String name;
Subject subObj;
public Student(int id, String name, Subject subObj) {
this.id = id;
this.name = name;
this.subObj = subObj;
}
// Default version of clone() method. It creates shallow copy of an object.
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Solution {
public static void main(String[] args) {
Subject subject = new Subject("Computer Science");
Student stuObj1 = new Student(3213, "Kulwinder Kaur", subject);
Student stuObj2 = null;
try {
//Explicitly Type conversion is req
stuObj2 = (Student) stuObj1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
// Print CompSci
System.out.println(stuObj1.subObj.list[3]);
stuObj2.subObj.list[3] = "Physical Education";
System.out.println(stuObj1.subObj.list[3]);
}
}
During deep copy we create the copy of the source object. But, unlike shallow copy, if the source objects contain and reference objects then copies of those objects will also get created with the help of clone() method. It will make both the source and target object independent of each other. If we make any change to either object it will not get reflected to another object.
Java Implementation of Deep Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.*;
import java.lang.*;
import java.io.*;
class Subject implements Cloneable {
String list[] = new String[4];
public Subject(String optionalSubject) {
list[0] = "Physics";
list[1] = "Chemistry";
list[2] = "Maths";
list[3] = optionalSubject;
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Student implements Cloneable {
int id;
String name;
Subject subObj;
public Student(int id, String name, Subject subObj) {
this.id = id;
this.name = name;
this.subObj = subObj;
}
protected Object clone() throws CloneNotSupportedException {
Student emp = (Student) super.clone();
emp.subObj = (Subject) subObj.clone();
return emp;
}
}
public class Solution {
public static void main(String[] args) {
Subject subObject = new Subject("Computer Science");
Student stuObj1 = new Student(3213, "Kulwinder Kaur", subObject);
Student stuObj2 = null;
try {
stuObj2 = (Student) stuObj1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println(stuObj1.subObj.list[3]);
stuObj2.subObj.list[3] = "Physical Education";
System.out.println(stuObj1.subObj.list[3]);
}
}
Output 2: for Deep Copy Implementation