首页 > 解决方案 > 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 方法。

你能帮我理解这个吗?

标签: javainheritance

解决方案


您正在尝试使用这两种方法获取相同类型的实体,不是吗?在这种情况下设计是不正确的:你应该参数化整个接口,而不是单独的每个方法:

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;  }

推荐阅读