在Java接口中声明参数子类型,在Java实现方法中使用子类型
我想在接口中声明一个方法,其中实现类中定义的方法的参数可以是特定 java 类的子类型,例如:
interface Processor{
processRequest( Request r);
}
public class SpecialRequest extends Request{...}
public class SpecialProcessor implements Processor{
processRequest(SpecialRequest r){...}
}
但我在 SpecialProcessor 中收到错误,因为它没有正确实现 Processor 接口。我可以在 Processor 接口中更改哪些内容以允许 SpecialProcessor 中的定义起作用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以输入
处理器
:You can type
Processor
:没错 - 请记住,调用者不应该知道正在使用接口的具体实现。他们只知道他们可以将
Request
(任何请求)传递给processRequest
,而您的实现对参数施加了更严格的约束,导致某些方法调用的类型不正确。如果你想这样做,你需要向接口添加一个通用参数,如下所示:
这样,想要传递“正常”请求的调用者将必须声明一个变量/字段,您的类可以分配给该变量/字段。
Processor
- 并且您的 SpecialProcessor 不再与此绑定匹配,因此无法分配,并且将在编译时正确拒绝。自己处理特殊请求的调用者可以使用 ProcessorThat'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) toprocessRequest
, 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:
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 aProcessor<SpecialRequest>
variable/field, which your class can be assigned to.