lundi 27 juin 2022

Can a public abstract class create an object of itself inside itself?

I'm learning the chain of responsibility pattern and this is given as the example:

abstract public class AbstractRequest {

    // Each request is identified by a an integer
    // FireRequest: 1
    // LowFuelRequest: 2
    private int requestCode;

    public AbstractRequest(int requestCode) {
        this.requestCode = requestCode;
    }

    public int getRequestCode() {
        return requestCode;
    }
}

abstract public class AbstractHandler {

    private AbstractHandler next;

    public AbstractHandler(AbstractHandler next) {
        this.next = next;
    }

    public void setNext(AbstractHandler next) {
        this.next = next;
    }

    public void handleRequest(AbstractRequest request) {
        if (next != null) {
            next.handleRequest(request);
        }
    }
}

I can't understand how an abstract class can create an object.

Moreover, how can a class be instantiated inside itself?

Wouldn't it cause indefinite recursion?

EDIT: The above questions are raised w.r.t this line: private AbstractHandler next;

Aucun commentaire:

Enregistrer un commentaire