Posted by Unknown on 1:39 AM
Labels:

The default behaviour of an object’s clone() method automatically yields a shallow copy. So to achieve a deep copy the classes must be edited or adjusted.

Shallow copy: If a shallow copy is performed on obj-1 then it is copied but its contained objects are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable interface.




Deep copy: If a deep copy is performed on obj-1 then not only obj-1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead.




class A {
int l = 1;
}

class B extends A implements Cloneable {
int m = 2;
}

class CloneDemo4 extends B {
int n = 3;
A a = new A();

public static void main(String[] args) throws CloneNotSupportedException {
CloneDemo4 c = new CloneDemo4();
CloneDemo4 c2 = (CloneDemo4) c.clone();

System.out.println(c.l);
System.out.println(c2.l);
System.out.println(c.m);
System.out.println(c2.m);
System.out.println(c.n);
System.out.println(c2.n);

System.out.println(c.a == c2.a);
}

protected Object clone() throws CloneNotSupportedException {
// First, perform a shallow copy.

CloneDemo4 temp = (CloneDemo4) super.clone();

if (a != null)
temp.a = new A();

return temp;
}
}

0 comments: