gpt4 book ai didi

java - 将子类添加到数组列表中,然后高级

转载 作者:行者123 更新时间:2023-12-02 05:10:55 26 4
gpt4 key购买 nike

private ArrayList<Doctor> doctors = new ArrayList<Doctor>();

doctors.add(new Doctor());
doctors.add(new Doctor());
doctors.add(new Doctor());

doctors.add(new Surgeon());
doctors.add(new Surgeon());
doctors.add(new Surgeon());

for (Doctor doctor: doctors) {
if (doctor.getAssignedPatient() != null) {
if (doctor.aDayPasses()) {
System.out.println("A " + convertSpecialism(doctor.getSpecialism()) + " treated their patient.");
shortBreak();
}
} else {
break;
}
}

工作正常,但是当我尝试这样做时:

        for (Surgeon doctor: doctors) {
if (doctor.getAssignedPatient() != null) {
if (doctor.aDayPasses()) {
System.out.println("A " + convertSpecialism(doctor.getSpecialism()) + " treated their patient.");
shortBreak();
}
} else {
break;
}
}

存在语法错误,如何 for 循环遍历我添加到 doctor 类型的 ArrayList 中的外科医生。

假设外科医生延伸医生。

最佳答案

用两个词来说:你不能。因为 ArrayList 包含 Doctor,并且您无法将该列表作为 Surgeons 列表进行迭代,因为 Java 不支持隐式向下转型。这与在没有明确向下转型的情况下将 Doctor 分配给 Surgeon 相同。

因此,如果您想获得 Surgeon,您应该将其显式转换为 Surgeon,如下所示:

   for(Doctor d :doctors){
if (d instanceof Surgeon){
Surgeon s = (Surgeon) d;
...
}
}

但这是非常糟糕的做法,您不应该这样做。

关于java - 将子类添加到数组列表中,然后高级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27346888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com