As per the JAVA documentation, the super.clone() when called returns a shallow copy of the object. In the code below I have two objects name and id
class Subject {
private String name;
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Subject(String s) {
name = s;
}
}
class Student implements Cloneable {
//Contained object
private Subject subj;
private String name;
public Subject getSubj() {
return subj;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public Student(String s, String sub) {
name = s;
subj = new Subject(sub);
}
public Object clone() {
//shallow copy
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
public class CopyTest {
public static void main(String[] args) {
//Original Object
Student stud = new Student("John", "Algebra");
System.out.println("Original Object: " + stud.getName() + " - "
+ stud.getSubj().getName());
//Clone Object
Student clonedStud = (Student) stud.clone();
System.out.println("Cloned Object: " + clonedStud.getName() + " - "
+ clonedStud.getSubj().getName());
stud.setName("Dan");
stud.getSubj().setName("Physics");
System.out.println("Original Object after it is updated: "
+ stud.getName() + " - " + stud.getSubj().getName());
System.out.println("Cloned Object after updating original object: "
+ clonedStud.getName() + " - " + clonedStud.getSubj().getName());
}
}
Output is:
Original Object: John - Algebra
Cloned Object: John - Algebra
Original Object after it is updated: Dan - Physics
Cloned Object after updating original object: John - Physics
In this example, all I did is, implement the class that you want to copy with Clonable interface and override clone() method of Object class and call super.clone() in it. If you observe, the changes made to "name" field of original object (Student class) is not reflected in cloned object but the changes made to "name" field of contained object (Subject class) is reflected in cloned object. This is because the cloned object carries the memory address of the Subject object but not the actual values. Hence any updates on the Subject object in Original object will reflect in Cloned object.