Java 核心技术(第八版)卷1:基础知识:例6-2P215CloneTest

import java.lang.constant.Constable;
import java.util.*;
//本程序演示了克隆 功能  Cloning
public class CloneTest {
    public static  void main(String []args)
    {
        try
        {
            Employee original=new Employee("John Q.Public",50000);
            original.setHireDay(2000,1,1);

            Employee copy=original.clone();
            copy.raiseSalary(10);
            copy.setHireDay(2002,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;
        hireDay=new Date();
    }
    public Employee clone() throws CloneNotSupportedException
    {
        //调用Object.clone()
        Employee cloned=(Employee) super.clone();
        //克隆可以更改的字段
        cloned.hireDay=(Date) hireDay.clone();
        return cloned;
    }
    public String getName()
    {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public void setHireDay(int year,int month,int day)
    {
        Date newHireDay=new GregorianCalendar(year,month-1,day).getTime();
        hireDay.setTime(newHireDay.getTime());

    }
    public Date getHireDay()
    {
        return hireDay;
    }
    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;
}

运行结果:

Original=Employee[name=John Q.Public,salary=50000.0hireDay=Sat Jan 01 00:00:00 CST 2000]
Copy=Employee[name=John Q.Public,salary=55000.0hireDay=Tue Dec 31 00:00:00 CST 2002]

你可能感兴趣的:(Java,java,开发语言,原型模式)