Assignment OOP
Assignment OOP
Deep copy is particularly useful when working with complex data structures that contain
references to other objects or data structures. Without deep copy, changes made to a
copy of a complex data structure could inadvertently affect the original data structure.
One main fact of deep copy is that it is commonly used in object-oriented programming
to create a new instance that has the same values as an existing instance but with a
separate memory location. This is important because it allows for safe and independent
modification of the new instance without affecting the original, improving the reliability
of the program.
Example in java:
import java.util.Scanner;
public class CloneExample implements Cloneable {
private String name;
private int age;
public CloneExample(String name, int age){
this.name = name;
this.age = age;
}
public void displayData(){
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
}
public static void main(String[] args) throws CloneNotSupportedException {
Scanner Salar =new Scanner(System.in);
System.out.println("Enter your name ");
String name = Salar.next();
System.out.println("Enter your age ");
int age = Salar.nextInt();
CloneExample std = new CloneExample(name, age);
System.out.println("Contents of the original object");
std.displayData();
System.out.println("Contents of the copied object");
CloneExample copiedStd = (CloneExample) std.clone();
copiedStd.displayData();
}
}