I am very new and learning java,I want to perform deep cloning without serialization ,I read some articles from internet and still in doubt about deep cloning without serialization.So i want to know is there any other rules that I have to follow to do deep cloning, below is my program
Department.java
package com.deepclone;
public class Department {
private int id;
private String name;
public Department(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Employee.java
package com.deepclone;
public class Employee implements Cloneable {
private String employeeId;
private String empName;
private Department department;
public Employee(String employeeId, String empName, Department department) {
this.employeeId = employeeId;
this.empName = empName;
this.department = department;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Employee employee = new Employee(employeeId, empName, new Department(
department.getId(), department.getName()));
return employee;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
TestCloning.java
package com.deepclone;
public class TestClonning1 {
public static void main(String[] args) throws CloneNotSupportedException {
Department hrDepartment = new Department(10, "HR");
Employee employee = new Employee("1", "rajeev", hrDepartment);
System.out.println(employee.getDepartment().getName());
Employee cloneEmployee = (Employee) employee.clone();
System.out.println(cloneEmployee.getDepartment().getName());
cloneEmployee.getDepartment().setName("it");
System.out.println(employee.getDepartment().getName());
System.out.println(cloneEmployee.getDepartment().getName());
}
}
output
HR
HR
HR
it
is there any other alternative to achive deep cloning without serialization...if yes then give link.