这里我有一个抽象类 Person 和多个子类:
public abstract class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
public class ComputerScientist extends Person {
public String job;
public ComputerScientist(String name, String job) {
super(name);
this.job = job;
}
}
public class SoftwareEngineer extends Person {
public String job;
public SoftwareEngineer(String name, String job) {
super(name);
this.job = null;
}
}
这就是我运行的:
public static void main(String[] args) {
List<Person> people = new ArrayList<Person>();
person.add(new ComputerScientist("ben", "job"));
person.add(new SoftwareEngineer("larry", "job"));
Random r = new Random();
Person person = people.get(r.nextInt(people.size() - 1);
}
人与列表中的人变得相同,我如何将其作为人克隆。克隆和新实例不起作用。
我可能可以使用复制方法来做到这一点(需要我重写大量代码),但是有没有任何(也许更有效)的方法可以做到这一点?
最佳答案
您可以创建一个方法来创建 Person 的新对象(根据子类),并创建另一个方法来复制新对象中的状态。请参阅以下方法以了解其基本实现。
public abstract class Person{
...//your states and methods
protected void copy(Person copiedPerson){
copiedPerson.name = this.name;
}
public abstract Person getCopyPerson();
}
public class SoftwareEngineer extends Person{
....//your states and methods
@override
protected void copy( Person copiedPerson ){
super(copiedPerson);
copiedPerson.job = this.job;
}
@override
public Person getCopyPerson(){
Person copyPerson = new SoftwareEngineer();
copy(copyPerson);
return copyPerson;
}
}
现在,每当您获取 Person 的对象时,只需对其调用 getCopyPerson()
即可获取复制对象。
关于java - 使用java中的父类(super class)对象创建未知子类的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49406205/