Java 在实现中绑定不同的接口方法以接受固定但不同的参数
我有如下几个接口:ResponseInterface、InputInterface、ClientInterface 客户端接口有几种方法,如下所示:Java 在实现中绑定不同的接口方法以接受固定但不同的参数,java,Java,我有如下几个接口:ResponseInterface、InputInterface、ClientInterface 客户端接口有几种方法,如下所示: public interface ClientInterface { public ResponseInterface method1 (InputInterface in); public ResponseInterface method2 (InputInterface in); } 在实现端,我有两种不同的Resp
public interface ClientInterface {
public ResponseInterface method1 (InputInterface in);
public ResponseInterface method2 (InputInterface in);
}
在实现端,我有两种不同的ResponseInterface实现和两种InputInterface实现
在ClientImpl中,我想做如下操作:
public class ClientImpl implments ClientInterface {
@Override
public ResponseImpl1 method1 (InputImpl1 input) {
...
}
@Override
public ResponseImpl2 method2 (InputImpl2 input) {
...
}
}
但这是行不通的。将ResponseImpl1和ResponseImpl2指定为这两个方法的返回类型没有问题,但编译器不允许设置输入类型(因为这样这些方法就不会被视为对接受InputInterface对象的原始接口方法的重写)
我的问题是,如何强制这些方法的实现只接受某个类(当然是实现InputInterface的类)
我知道当界面中只有一个操作时,如何做到这一点:
public class SomeImpl implements SomeInterface <ConcreteInputClass> {
@Override
public SomeResponseImpl interfaceMethod(ConcreteInputClass input) {
...
}
}
public类SomeImpl实现SomeInterface{
@凌驾
公共SomeResponseImpl接口方法(ConcreteInputClass输入){
...
}
}
但当接口有多个方法时,我该怎么做呢?这与操作的数量无关,而是动态类参数的数量
public interface ClientInterface<T1 extends InputInterface, T2 extends InputInterface> {
public ResponseInterface method1 (T1 in);
public ResponseInterface method2 (T2 in);
}
公共接口客户端接口{
公共响应接口方法1(T1英寸);
公共响应接口方法2(T2英寸);
}
那么,以下各项是否正常:
public class ClientImpl implements ClientInterface<InputImpl1,InputImpl2> {
@Override
public ResponseImpl1 method1 (InputImpl1 input) {
return null;
}
@Override
public ResponseImpl2 method2 (InputImpl2 input) {
return null;
}
}
公共类ClientImpl实现ClientInterface{
@凌驾
公共响应IMPL1方法1(InputImpl1输入){
返回null;
}
@凌驾
公共响应IMPL2方法2(输入IMPL2输入){
返回null;
}
}
Java方法调用是单一分派,这意味着只有调用方法的对象的类型才能确定所使用的实现
您似乎想要的是称为多重分派(在运行时检查参数类型并确定实现),并且可以进行模拟,例如使用