实现通用接口

问题描述:

我有一个接口Exec的实现通用接口

public interface Exec<T, U> { 
    U execute(final T context); 
} 

现在我可以有它实现接口Exec的如下

public class BatchExec<T, U> implements Exec<List<T>, List<U>> 

一类我的疑问是Exec的接受T和U为类型参数和在这种情况下,我们将它作为List和List传递,但BatchExec期望T和U?

+3

的'T'和''U'是完全无关的'T'和'U'在'Exec的'。将它们想象为方法参数 - 多个方法可以具有相同名称的参数。 –

正如Oliver Charlesworth指出的那样,在BatchExex<...>UT比在Exec<T, U>不同。即如果声明BatchExec这样的:

public class BatchExec<T, U> implements Exec<List<T>, List<U>> 

然后执行方法签名将包含List<T>List<U>

public List<U> execute(List<T> context) 

这可能会造成混乱,以便让我们创建与其他类型参数的OtherbatchExec

public class OtherBatchExec<P, Q> implements Exec<List<P>, List<Q>> { 
    @Override 
    public List<Q> execute(List<P> context) { 
     return null; 
    } 

} 

只是为了证明它,你可以用同样的方式调用它们的构造函数:

Exec<List<String>, List<Integer>> exec = new BatchExec<String, Integer>(); 
Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<String, Integer>(); 

为了便于阅读,我也将类型参数添加到构造函数调用中。您可以使用diamond operator太:在`BatchExec ,>

Exec<List<String>, List<Integer>> exec = new BatchExec<>(); 
Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<>();