The clone() method

The java.lang.Object is having a clone() method . The method is to get a copy of particular object.To get a clone copy the class should implement the Cloneable interface. If it is not implemented it ,  CloneNotSupportedException will be thrown.

Let us learn the concept with an example.

public class Employee implements Cloneable {
private int id;
private String name;
public Employee(int number, String name) {
this.id = number;
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;
}
public static void main(String[] args) {
Employee employee = new Employee(1, "Bijoy");
try {
Employee emp = (Employee) employee.clone();
System.out.println("Clone copy : " + "id = " + emp.getId() + " ;Name = " + emp.getName());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}

The class is implementing the Cloneable interface.So  second object will be the copy of first object.

Output

Clone copy : id = 1 ;Name = Bijoy

Now , just remove the ‘implements Cloneable’ from the class declaration .Cmpile and run the code again . CloneNotSuppotedException is throwing.