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; and one primitive variable num. When the super.clone() method is called on the first object, it seems to be creating a deep copy of the objects(name and id) in addition to an expected copy of only num. After cloning the object obj, I have changed its name and id fields. These changes should be reflected in the cloned object if a shallow copy was being made. Am I right?
public class Cloning implements Cloneable {
String name;
int num;
Integer id;
Cloning(String name,int num,Integer id)
{
this.name = name;
this.num = num;
this.id = id;
}
public Object clone()
{
try
{
return super.clone();
}
catch(CloneNotSupportedException E)
{
System.out.println(E.getMessage());
return null;
}
}
public void print()
{
System.out.println(name);
System.out.println(num);
System.out.println(id);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Cloning obj = new Cloning("Annu",203,new Integer(3));
Cloning obj1 = (Cloning)obj.clone();
obj.name = "Annu_modified";
obj.num = 204;
obj.id = new Integer(4);
obj.print();
obj1.print();
}
}
I get the following output on running the code:
Annu_modified
204
4
Annu
203
3