Thahleel al-Aleem
Thahleel al-Aleem

Reputation: 781

Adding sub classes to array lists then advanced for

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;
            }
        }

Works fine however when I try to do this:

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

There is a syntax error, how do I for loop through the surgeons I have added to the ArrayList of type doctor.

Assume that Surgeon extends doctor.

Upvotes: 0

Views: 85

Answers (3)

manzur
manzur

Reputation: 692

In two words: you can't. Because ArrayList contains Doctor, and you can't iterate that list as a list of Surgeons as Java doesn't support implicit downcasting. It is the same as assigning Doctor to Surgeon without explicitly downcasting.

So if you want to get Surgeon, you should explicitly convert it to Surgeon like this:

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

But that's very bad practice and you shouldn't be doing it.

Upvotes: 2

Tkachuk_Evgen
Tkachuk_Evgen

Reputation: 1354

You can do like this:

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

Upvotes: 0

DavidGSola
DavidGSola

Reputation: 727

You can't create a for-each loop (for (SubClass subClass : superClasses)) because the compiler cannot ensure that there are only objects of type SubClass (Surgeon) in there.

Upvotes: 0

Related Questions