The missing factor of Clone() in Java

Many Java developers, event most experienced, do not have a insight of how exactly Clone() works in Java. I will try to simplify the Clone() concept in this article.

We all know that Clone() is used to create a copy of an object, however Clone() in Java is “shallow copy”.

Shallow Copy v/s Deep Copy:

Shallow copy creates new copy of primitive types (int, boolean, String etc.), but copies reference of inner objects to the new cloned class. Which means both original and cloned object will point to the same inner objects.

class Course implements Cloneable {
int courseId;
String subject;
object clone() throws CloneNotSupportedException {
return super.clone(); //here subject reference is copied to the cloned object
}
}
class Student {
int id;
Course courseFullTime= new Course();
Course coursePartTime;
try {
coursePartTime = (Course)courseFullTime.clone();
} catch (CloneNotSupportedException e) { ….}
……..
}

Deep copy creates new copy of primitive types, but also creates a new copy of the inner objects.

class Course implements Cloneable {
int courseId;
Subject subject;
object clone() throws CloneNotSupportedException {
Course course = (Course) super.clone();
course.subject = (Subject) subject.clone();
return super.clone();
}
}
class Student {
int id;
Course courseFullTime = new Course();
Course coursePartTime;
try {
coursePartTime = (Course)courseFullTime.clone();
} catch (CloneNotSupportedException e) { ….}
……..
}

For deep copy I have created a clone of inner objects, assuming that inner objects implements Cloneable interface and consists of only primitive type attributes. We have to do the same for all levels of nested inner objects in order to clone by deep copy.