AIM: Copy an object to a new object.
Normal assignment to copy an object will create two references to the same object.
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;
e2.setname("Eknath"); // This will update the name in e1 also.
We want : Two separate but identical objects?
e2 should be initialized to a disjoint copy of e1.How can we do this?
clone() methodObject defines a method clone()<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.
Object does not have access to the private instance variables.e1 from scratch.What could go wrong with a bitwise copy???
What if we add an instance variable Date (object) to Employee ?
public class Employee{
private String name;
private double salary;
private Date birthday;
...
public void setname(String n){
name = n;
}
public void setbday(int dd, int mm, int yy){
birthday.update(dd,mm,yy);
}
}
...
Employee e1 = new Employee("Dhruv" , 21500.0);
Employee e2 = e1.clone();
e2.setname("Eknath"); // e1 name will not be updated.
e2.setbday(16,4,1997); // e1 bday will be updated.
update() updates the components of the Date object.Bitwise copy made by e1.clone() copies reference to the embedded Date.
e2.birthday and e1.birthday refers to the same object!e2.setbday also affects e1.birthday<aside> 💡 Bitwise copy is a shallow copy. i.e. , nested mutable references are copied verbatim.
</aside>
<aside> 💡 Deep copy recursively clones nested objects.
</aside>