Cloneable Interface in Java

A class who wants its object to be cloned (copied) must define Cloneable Interface and should override Object.clone method.

Cloneable Interface in Java

A class who wants its object to be cloned (copied) must define Cloneable Interface and should override Object.clone method.

Cloneable Interface in Java

Cloneable interface in a class points out that it is legal for Object.clone() method to copy instances of that class. In simple words, a class defines Cloneable Interface if it wants its object to be cloned. However, it is not necessary that a Cloneable interface contains a clone() method.

clone( ) method creates a duplicate object that has distinct identity but similar content.

Class that implements Cloneable Interface should override Object.clone method.

It must also be noted that just invoking an Object's clone method on an instance does not implement the Cloneable interface. If an object's class does not implement the Cloneable interface, CloneNotSupportedException is thrown.

CloneNotSupportedException is also thrown to indicate that a particular object should not be cloned.

Example of Clone method:

import java.util.*;
public class CloneTest{
public static void main(String[] args){

Employee emp = new Employee("Amardeep", 50000);
emp.setHireDay(2005,0,0);
Employee emp1 = (Employee)emp.clone();
emp1.raiseSalary(20);
emp1.setHireDay(2008, 12, 31);
System.out.println("Employee=" + emp);
System.out.println("copy=" + emp1);
}
}
class Employee implements Cloneable{
public Employee(String str, double dou){
name = str;
salary = dou;
}
public Object clone(){
try{
Employee cloned = (Employee)super.clone();
cloned.hireDay = (Date)hireDay.clone();
return cloned;
}
catch(CloneNotSupportedException e){
System.out.println(e);
return null;
}
}
public void setHireDay(int year, int month, int day){
hireDay = new GregorianCalendar(year,month - 1, day).getTime();
}
public void raiseSalary(double byPercent){
double raise = salary * byPercent/100;
salary += raise;
}
public String toString(){
return "[name=" + name+ ",salary=" + salary+ ",hireDay=" + hireDay+ "]";
}
private String name;
private double salary;
private Date hireDay;
}

Output:

C:\help>javac CloneTest.java

C:\help>java CloneTest
Employee=[name=Amardeep,salary=50000.0,hireDay=Tue Nov 30 00:00:00 GMT+05:30 2004]
copy=[name=Amardeep,salary=60000.0,hireDay=Wed Dec 31 00:00:00 GMT+05:30 2008]