declare parameter subtype in Java interface, use subtypes in Java implementing methods

半腔热情 提交于 2019-12-05 20:08:37

You can type Processor:

public interface Processor<R extends Request> {
    void processRequest(R r);
}


public class SpecialProcessor implements Processor<SpecialRequest> {
    public void processRequest(SpecialRequest r) {
       ...
    }
}

That's right - remember that a caller shouldn't know what specific implementation of the interface is being used. They just know that they can pass a Request (any Request) to processRequest, whereas your implementation is imposing a stricter constraint on the argument that would cause certain method calls not to be type-correct.

If you want to do this, you'll need to add a generic parameter to the interface, something like the following:

interface Processor<R extends Request> {
    void processRequest(R r);
}

public class SpecialProcessor implements Processor<SpecialRequest> {

    public void processRequest(SpecialRequest r) { ... }

}

This way, callers that want to pass in "normal" requests will have to declare a variable/field of type Processor<Request> - and your SpecialProcessor no longer matches this bound, so cannot be assigned, and will correctly be rejected at compile-time. Callers that are dealing with special requests themselves can use a Processor<SpecialRequest> variable/field, which your class can be assigned to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!