集册 Java实例教程 创建深拷贝

创建深拷贝

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

660
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
创建深拷贝

public class CloneTest2

{

    public static void main(String[] args)

    {//from N o w  J a v a  . c o m

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

    emp1.setSalary(40000.0);

    emp1.address = new Address("1300 N. Main Street","New York", "CA", "99999");

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


    System.out.println("**** after cloning ****\n");

    printEmployee(emp1);

    printEmployee(emp2);


    emp2.setLastName("S");

    emp2.address = new Address("2503 N. 6th Street","L.A.", "CA", "93722");

    /*来自 
     时代Java公众号*/

    System.out.println(

      "**** after changing emp2 ****\n");

    printEmployee(emp1);

    printEmployee(emp2);


    }


    private static void printEmployee(Employee e)

  {

    System.out.println(e.getFirstName() + " " + e.getLastName());

    System.out.println(e.address.getAddress());

    System.out.println("Salary: " + e.getSalary());

    System.out.println();

  }


}


class Employee implements Cloneable

{

  private String lastName;

  private String firstName;

  private Double salary;


  public Address address;


  public Employee(String lastName, String firstName)

  {

    this.lastName = lastName;

    this.firstName = firstName;

    this.address = new Address();

  }


  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;

    try

    {

      emp = (Employee) super.clone();

      emp.address = (Address)address.clone();

    }

    catch (CloneNotSupportedException e)

    {

      return null;   // will never happen

    }

    return emp;

  }


  public String toString()

  {

    return this.getClass().getName() + "["

        + this.firstName + " "

        + this.lastName + ", "

        + this.salary + "]";

  }

}


class Address implements Cloneable

{

  private String street;

  private String city;

  private String state;

  private String zipCode;


  public Address()

  {

    this.street = "";

    this.city = "";

    this.state = "";

    this.zipCode = "";

  }


  public Address(String street, String city,

           String state, String zipCode)

  {

    this.street = street;

    
展开阅读全文