集册 Java实例教程 实现克隆方法

实现克隆方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

576
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
实现克隆方法

public class CloneTest

{

    public static void main(String[] args)
    /** 
     来自 时   代    Java - nowjava.com**/

    {

    Employee emp1 = new Employee("M", "A");

    emp1.setSalary(40000.0);

    Employee emp2 = (Employee)emp1.clone();

    emp1.setLastName("Smith");

    System.out.println(emp1);

    System.out.println(emp2);

    }

}


class Employee

{

  private String lastName;//from N o w J a v a . c o m

  private String firstName;

  private Double salary;


  public Employee(String lastName, String firstName)

  {

    this.lastName = lastName;

    this.firstName = firstName;

  }


  public String getLastName()

  {

    return this.lastName;

  }


  public void setLastName(String lastName)

  {

    this.lastName = lastName;

  }


  public String getFirstName()

  {

    return this.firstName;

  }


  public void setFirstName(String firstName)

  {

    this.firstName = firstName;

  }


  public Double getSalary()

  {

    return this.salary;

  }


  public void setSalary(Double salary)

  {

    this.salary = salary;

  }


  public Object clone()

  {

    Employee emp;

    emp = new Employee(

      this.lastName, this.firstName);

    emp.setSalary(this.salary);

    return emp;

  }


  
展开阅读全文