📄 clonetest.java.bak
字号:
import java.util.*;
public class CloneTest{
public static void main(String[] args)
{ try
{//某雇员在2000年1.1被雇佣,在同年年底涨工资,调用copy函数在原有数据的基础上
//只需修改日期,工资这两个数据其余不变
Employee original=new Employee("John Q.public",5000);
original.setHireDay(2000,1,1);
Employee copy=original.clone();
copy.raiseSalary(10);
copy.setHireDay(2000,12,31);
System.out.println("original="+original);
System.out.println("copy="+copy);
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
class Employee implements Cloneable
{
public Employee(String n,double s)
{ name=n;
salary=s;
}
public Employee clone() throws CloneNotSupportedException
{
//call object.clone()
Employee cloned=(Employee)super.clone();
//clone mutable fields
cloned.hireDay=(Date)hireDay.clone();
return cloned;
}
/**
Set the hire day to a given date
@param year the year of the hire day
@param month the month of the hire day
@param day the day of the hire day
*/
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 "Employee[name="+name+",salary="+salary+",hireDay="+hireDay+"]";
}
private String name;
private double salary;
private Date hireDay;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -