6

I want to declare a method in an interface where the parameter of the method defined in implementing classes can be a subtype of a specific java class for example:

interface Processor{
      processRequest( Request r);
}

public class SpecialRequest extends Request{...}

public class SpecialProcessor implements Processor{

      processRequest(SpecialRequest r){...}
}

but I get errors in the SpecialProcessor because it doesn't properly implement the Processor interface. What can I change in the Processor interface to allow the definition in the SpecialProcessor to work?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user592672
  • 61
  • 2

2 Answers2

10

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) {
       ...
    }
}
Mark Peters
  • 80,126
  • 17
  • 159
  • 190
3

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.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228