我正在建立一个项目。要求之一是生成具有相同属性但随机不同值的对象。我尝试使用深度复制,但不确定在概念上是否正确。
Person
类,它是从抽象类Character
继承的。ScenarioGenerator
,我将使用getRandomPerson
方法来创建Person
类的实例。任何建议的帮助都将受到高度赞赏。
这是我的Person
课程的一部分:
public class Person extends Character {
private Random random;
private boolean pregnant;
private boolean isYou;
Person(int age, Profession profession ,Gender gender, BodyType bodyType, boolean isPregnant) {
super(age, gender, bodyType);//pass the attributes to the super class called Character
}
Person (Person otherPerson) { //copy constructor
this.age = otherPerson.getAge();
this.gender = otherPerson.getGender();
this.bodyType = otherPerson.getBodyType();
}
public Profession getProfession () { // One of the getters which generate random enum value
//only adults have profession
if (getAge()<=16 || getAge()>68) {
return Profession.NONE;
} else {
return Profession.values()[new Random().nextInt(Profession.values().length)];
}
}
// setters and getters
}
还有我的ScernarioGenerator
类的方法:
public class ScenarioGenerator {
public Person getRandomPerson() {
//need age, gender, bodyType, profession, pregnancy
Person people = new Person(person.getAge(), person.getProfession(), person.getGender(), person.getBodyType(), person.isPregnant());
Person clone = new Person(people);
return clone;
}
答案 0 :(得分:1)
如果您想要一个深度克隆的对象,则可以通过实现clone类并覆盖克隆函数来获得它,例如
public class Person extends Character implements Cloneable {......}
然后您可以通过
来获取新的深度复制对象Person clone=(Person) people.clone();