大概是java版本升级了,clone方法不严格写好像也没什么问题。
/** * Created by hero on 16-4-2. */ public class Company implements Cloneable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Company(String name) { this.name = name; } public Company clone() { Company company = null; try { company = (Company) super.clone(); } catch (CloneNotSupportedException e) { } return company; } } /** * Created by hero on 16-4-2. */ public class BusinessCard implements Cloneable { private String name; private Company company; public String getName() { return name; } public void setName(String name) { this.name = name; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public BusinessCard clone() { BusinessCard card = null; try { card = (BusinessCard) super.clone(); if(company!= null){ card.company = company.clone(); } } catch (CloneNotSupportedException e) { } //won‘t happen return card; } } public class Main { public static void main(String[] args) { BusinessCard card = new BusinessCard(); card.setName("张无忌"); card.setCompany(new Company("武当")); BusinessCard card1 = card.clone(); card1.setCompany(new Company("少林")); System.out.println(card.getName() + ", " + card.getCompany().getName()); System.out.println(card1.getName() + ", " + card1.getCompany().getName()); } }
时间: 2024-11-05 12:06:38