AIM: Copy an object to a new object.

Copying an object


The clone() method

<aside> 💡 e1.clone() returns a bitwise copy of e1.

</aside>

public class Employee{
	private String name;
	private double salary;

	public Employee(String n, double s){
		name = n;
		salary = s;
	}

	public void setname(String n){
		name = n;
	}
}
....
....
Employee e1 = new Employee("Dhruv", 21500.0);
Employee e2 = e1.clone();

e2.setname("Eknath"); // This will NOT update the name in e1.

What could go wrong with a bitwise copy???


Shallow Copy

<aside> 💡 Bitwise copy is a shallow copy. i.e. , nested mutable references are copied verbatim.

</aside>


Deep Copy

<aside> 💡 Deep copy recursively clones nested objects.

</aside>