java - java中的通用接口继承
问题描述
我使用以下方法在 Java 中创建了一个接口:
interface ReaderInterface{
public <k,v> Map<k,v> fetch(k id);
public <k,v> Map<k,v> fetchAll();
}
然后我创建了一个实现该接口的类:
class JSONreaderImpl implements ReaderInterface{
public Map<String, String> fetchAll(){
// This compiler is allowing to be override from interface \
}
public Map<String, String> fetch(String id){
// This is not being considered as an override method, compiler throwing an error to implement the fetch method
}
}
我的问题是为什么 fetchAll 方法被视为在特定类上创建它的覆盖方法以及为什么不 fetch 方法。
你能帮我理解这个吗?
解决方案
您正在尝试使用这两种方法获取相同类型的实体,不是吗?在这种情况下设计是不正确的:你应该参数化整个接口,而不是单独的每个方法:
interface ReaderInterface<k, v> {
public Map<k, v> fetch(k id);
public Map<k, v> fetchAll();
}
class JSONreaderImpl implements ReaderInterface<String, String> {
public Map<String, String> fetchAll() { return null; }
public Map<String, String> fetch(String id) { return null; }
}
否则(分别参数化每个方法,您打算允许像
public Map<String, Boolean> fetchAll() { return null; }
public Map<Integer, List<Double>> fetch(Integer id) { return null; }
推荐阅读
- c++ - min 的最佳实现是什么?
- node.js - 如何确保 Lambda 函数等待调用带有 await 的异步函数?
- javascript - 如何替换列表中每个字母的第一次出现?
- php - 从函数内的多个值进行数组搜索
- typescript - 有没有办法使用变量来实例化具有参数列表中可选参数的类?
- angular - 为什么我的初始 ngrx 状态不适用于 ngIf
- java - 如何引用添加到二叉树的方法?
- python - PYOMO:对抽象模型集的操作
- android - 为什么将 Glide 作为 ByteArray 的图像加载到 ImageView 时不会根据 EXIF 旋转它?
- tableau-api - 如何在仪表板中创建一个下拉或多选过滤器来过滤所有工作表?