我們拿簡歷為例
示例代碼
WorkExperience
public class WorkExperience {
private String time;
private String company;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public WorkExperience cusClone(){
WorkExperience experience = new WorkExperience();
experience.setCompany(this.company);
experience.setTime(this.time);
return experience;
}
}
Resume
public class Resume {
private String name;
private String age;
private String sex;
private WorkExperience experience;
public Resume(){}
public Resume(String name){
this.name = name;
this.experience = new WorkExperience();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public WorkExperience getExperience() {
return experience;
}
//注意下這里,對于對象,我們需要拷貝
public void setExperience(WorkExperience experience) {
this.experience = experience.cusClone();
}
public Resume cusClone(){
Resume resume = new Resume();
resume.name = this.name;
resume.age = this.age;
resume.sex = this.sex;
resume.setExperience(this.experience);
return resume;
}
}
使用
public static void main(String[] args) {
Resume resume = new Resume("mi");
resume.setAge("20");
resume.setSex("男");
WorkExperience experience = new WorkExperience();
experience.setTime("20110101-20140404");
experience.setCompany("baidu");
resume.setExperience(experience);
Resume resume1 = resume.cusClone();
resume1.getExperience().setCompany("sina");
System.out.println(resume == resume1);
System.out.println(resume.getExperience().getCompany());
System.out.println(resume1.getExperience().getCompany());
}
打印
false
baidu
sina