Hi, I have a code which will help you to get some information about the clone method in java. I think you will able to get information about clone method in java from this.
Code:
import java.util.*;
public class CloneJava
{
public static void main(String[] args)
{
Employee e = new Employee("Sanjay", 50000);
e.setHireDay(2005,0,0);
Employee e1 = (Employee)e.clone();
e1.raiseSalary(20);
e1.setHireDay(2008, 12, 31);
System.out.println("Employee=" + e);
System.out.println("copy=" + e1);
}
}
class Employee implements Cloneable
{
public Employee(String str, double dou)
{
name = str;
salary = dou;
}
public Object clone()
{
try
{
Employee eclone= (Employee)super.clone();
eclone.hireDay = (Date)hireDay.clone();
return eclone;
}
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;
}
Bookmarks