This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: Deep copy in java example program
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
In shallow copy of object only object reference will be copied and if we change any data inside object changes will reflect in cloned object also this means both are referring to same object.
Deep copy / Deep cloning in Java
In deep copy completely a new object will be created with same data.
If we change the data inside original object wont reflect in deeply cloned object.
Program #1: Java example program to demonstrate deep copy / deep cloning
Sample :
package com.shallowcopyvsdeppcopy;
public class Sample {
int a;
int b;
Sample (int a, int b){
this.a=a;
this.b=b;
}
}
Empclone :
package com.shallowcopyvsdeppcopy;
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
What is the difference between shallow copy and deep copy:
When we create a shallow copy of the object only reference will be copied
When we create deep copy of the object totally new object with same data will be created.
Shallow copy and deep copy will be done by using Cloneable interface in java.