Skip to content

Instantly share code, notes, and snippets.

@Audhil
Created July 30, 2020 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Audhil/7320d56d4345fb59a50d782b5ebda084 to your computer and use it in GitHub Desktop.
Save Audhil/7320d56d4345fb59a50d782b5ebda084 to your computer and use it in GitHub Desktop.
Deep Copy / clone in java - that supports changing member class data as well
public class DeepCloneDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Employee employee = new Employee("audhil", 31, new Address(11, 782382));
System.out.println("employee:" + employee);
Employee employee2 = (Employee) employee.clone();
System.out.println("employee2:" + employee2);
employee2.setAddress(new Address(33, 4342));
System.out.println("employee:" + employee);
System.out.println("employee2:" + employee2);
}
}
class Employee implements Cloneable {
String name;
int age;
Address address;
public Employee(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", address=" + address +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
Employee employee = (Employee) super.clone();
employee.setAddress((Address) address.clone());
return employee;
}
}
class Address implements Cloneable {
int doorNo;
long pinCode;
public Address(int doorNo, long pinCode) {
this.doorNo = doorNo;
this.pinCode = pinCode;
}
public int getDoorNo() {
return doorNo;
}
public void setDoorNo(int doorNo) {
this.doorNo = doorNo;
}
public long getPinCode() {
return pinCode;
}
@Override
public String toString() {
return "Address{" +
"doorNo=" + doorNo +
", pinCode=" + pinCode +
'}';
}
public void setPinCode(long pinCode) {
this.pinCode = pinCode;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment