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.

One thought on “The clone() method

  1. […] 4)clone() :- Returning  copy of a particular object. See more about clone() and example […]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">