我已经阅读过有关克隆对象的文档,我的结论是克隆对象是不好的做法。
使用与另一个值相同的值创建新对象的最佳方法之一是什么?
示例:
class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age){
this.age = age;
}
}
public class AnotherClass{
Student guy = new Student();
guy.setName("Mike");
guy.setAge(20);
Student guy2 = makeClone(guy); //now i get a new guy with the same values of the first guy
private Student makeClone(Student oldStudent){
Student newStudent = new Student();
newStudent.setName(oldStudent.getName());
newStudent.setAge(oldStudent.getAge());
return newStudent;
}
}