Deep diving into Cloning

Deep diving into Cloning

Employee.java (main object)

public class Employee implements Cloneable {
	private String employeeName;
	private Department dept;

	public String getEmployeeName() {
		return employeeName;
	}

	public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}

	public Department getDept() {
		return dept;
	}

	public void setDept(Department dept) {
		this.dept = dept;
	}

	public Employee(String emp, String empDept) {
		employeeName = emp;
		dept = new Department(empDept);
	}

	public Object clone() {
		try {
			return super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
			return null;
		}
	}
}

Client.java

public static void main(String[] args) {
		Employee emp = new Employee("Chris", "Sales");
		System.out.println("Original Object value - Employee Name:"
				+ emp.getEmployeeName() + " & department name:"
				+ emp.getDept().getDeptName());
		Employee clonedEmployee = (Employee) emp.clone();
		System.out.println("Cloned object value - Employee Name:"
				+ clonedEmployee.getEmployeeName() + " & department name:"
				+ clonedEmployee.getDept().getDeptName());
		// Now let's change values of Original Object
		emp.setEmployeeName("Peter");
		emp.getDept().setDeptName("Finance");
		System.out
		.println("Original Object value after it is modified - Employee Name:"
				+ emp.getEmployeeName()
				+ " & department name:"
				+ emp.getDept().getDeptName());
		System.out
		.println("Cloned object value after modification of original object" +
				" - Employee Name:"
				+ clonedEmployee.getEmployeeName()
				+ " & department name:"
				+ clonedEmployee.getDept().getDeptName());
	}

Deep Cloning Example

Deep Cloning Example
Deep Cloning Example

In case of Deep cloning unlike the Shallow cloning the all the fields of the original object is copied to the clone object including the object which was referenced by the original object. This process make a copy of the dynamically allocated memory pointed to by the fields.

In the above example even if the original object is modified and its values are changed then the cloned object is not changed including the reference object value since it does not refer to the same memory address.

Code Example for Deep Cloning:

In case of deep cloning the only change happens in the clone() method. Unlike Shallow cloning the super.clone() method is not called and instead an object is created using the new operator inside the clone() method.

public Object clone() {
	//Deep Copy process
		Employee e = new Employee(employeeName, dept.getDeptName());
		return e;
}

Hope you have enjoyed this article. Please feel free to provide your feedback and comments.
Previous Page

Download Complete Code:
Download Sample Code

Share This Post

One Response to "Deep diving into Cloning"

Post Comment