Shallow copy:
- Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
Example Program:
take a sample class
Step 1:
public class Sample {
int a;
int b;
Sample(int a, int b){
this.a=a;
this.b=b;
}
}
Step 2:
package com.oops;
public class empclone implements Cloneable {
Sample s;
int a;
empclone(int a, Sample s){
this.a=a;
this.s=s;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String[] args) {
empclone a= new empclone(2, new Sample(3,3));
empclone b=null;
try {
b=(empclone)a.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(a.s.a);
System.out.println(b.s.a);
a.s.a=12;
System.out.println(a.s.a);
System.out.println(b.s.a);
}
}
Output:
3
3
12
12
whenever we implements cloneable interface and ovverides clone() method
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
By default it will give shallow copy means if any objects presents in orninal class it simply gives reference so if we change anything in original object changes will made to copied/cloned object
because both are pointing to same object
Deep copy:
- A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
Example Program:
take a sample class
Step 1:
public class Sample {
int a;
int b;
Sample(int a, int b){
this.a=a;
this.b=b;
}
}
Step 2:
package com.oops;
public class empclone implements Cloneable {
Sample s;
int a;
empclone(int a, Sample s){
this.a=a;
this.s=s;
}
public Object clone()throws CloneNotSupportedException{
return new empclone(this.a, new Sample(this.s.a,this.s.a));
}
public static void main(String[] args) {
empclone a= new empclone(2, new Sample(3,3));
empclone b=null;
try {
b=(empclone)a.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(a.s.a);
System.out.println(b.s.a);
a.s.a=12;
System.out.println(a.s.a);
System.out.println(b.s.a);
}
}
Output:
3
3
12
3
whenever we implements cloneable interface and ovverides clone() method and instead of calling super.clone();
create new object with same data
new empclone(this.a, new Sample(this.s.a,this.s.a));
so it will create new object instead referring to same object as shallow
public Object clone()throws CloneNotSupportedException{
return new empclone(this.a, new Sample(this.s.a,this.s.a));
}
now we write our login in clone(); method
so complete object will be copied
this is deep cloning
No comments