How to declare class fields that have different types depending on the constructor parameters in Java

I’m new with Java and I’m trying to implement a class to encapsulate a clinic with a queue to determine the next patient to treat.

When initializing an instance of the class, I want to pass a triage type parameter to the constructor to decide how the clinic will select the next patient (frist in first out, or based on the gravity of the disease). Concretely, I want to have a single queue class field that is going to either be a Queue or a PriorityQueue depending on the triage parameter. I have a hard time to figure how to declare the queue field.

public enum TriageType {
    FIFO,
    GRAVITY
}

public class Clinic {

    public TriageType triageType;

    // This code block doesn't work, but it's the kind 
    // of behavior that I want
    if (triageType == TriageType.FIFO) {
        Queue<Patient> queue = new LinkedList<>()
    }
    else {
        PriorityQueue<Patient> queue = new PriorityQueue<>()
    }

    public Clinic(TriageType _triageType) {
        this.triageType = _triageType;
    }
}

Is it possible to do this without using two distinct classes?

Thanks a lot.

>Solution :

You cannot determine the static type of the field at runtime. Instead, you would use a common supertype, in this case Queue as the type.

If that doesn’t fit your needs, say if you need to use methods specific to PriorityQueue, the right solution would be to use polymorphism for this, declaring two separete classes, e.g., FIFOClinic and GravityClinic, which both declare the queue as they require it. The public methods that these classes would have in common should be extracted to a Clinic interface.

While the Clinic interface can be used in all instances where the public methods are called, the two classes have to be explicitly referenced during construction. If you require the construction to be uniform, i.e., depend only on a TriageType parameter, you could use the abstract factory pattern.

Leave a Reply