Shallow Copy:
A shallow copy of an object is a copy where only the references to the objects are copied, not the objects themselves. This means that the new object will share the same references to the objects inside the original object. If the internal objects are modified, the changes will be reflected in both the original and the copied objects.
public class ShallowEx {
int a;
int b;
public ShallowEx(){
this.a =100;
this.b = 200;
}
}
public class ShallowCopyMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
ShallowEx obj1 = new ShallowEx();
System.out.println("Before Copying");
System.out.println(obj1.a);
System.out.println(obj1.b);
//Copying Objects
ShallowEx obj2= obj1;
System.out.println(obj2.a);
System.out.println(obj2.b);
obj2.a=1000;
obj2.b=2000;
System.out.println("After Copying");
System.out.println("object1value "+obj1.a);
System.out.println("object1value "+obj1.b);
System.out.println("object1value "+obj2.a);
System.out.println("object1value "+obj2.b);
}
}
Output:
Before Copying
object1 a value 100
object1 b value 200
object2 a value 100
object2 b value 200
After Copying
object1 a value 1000
object1 b value 2000
object2 a value 1000
object2 b value 2000
Deep Copy:
A deep copy creates a completely independent copy of an object, including all the objects it refers to. This means the copied object and the original object are fully separate. Changes made to the copied object or its internal parts will not affect the original object, and vice versa.
public class DeepCopySupport implements Cloneable {
int a;
DeepCopySupport(int a){
this.a=a;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class DeepCopyMain {
public static void main(String[] args) throws CloneNotSupportedException {
// TODO Auto-generated method stub
DeepCopySupport obj1= new DeepCopySupport(90);
DeepCopySupport obj2= (DeepCopySupport) obj1.clone();
System.out.println("Before Deep Copy");
System.out.println("Object1 a value "+obj1.a);
System.out.println("Object2 a value "+obj2.a);
obj2.a=100;
System.out.println("After Deep Copy");
System.out.println("Object1 a value "+obj1.a);
System.out.println("Object2 a value "+obj2.a);
}
}
Output:
Before Deep Copy
Object1 a value 90
Object2 a value 90
After Deep Copy
Object1 a value 90
Object2 a value 100
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.