【问题标题】:How to implement function in interface with generic argument types?如何在具有通用参数类型的接口中实现函数?
【发布时间】:2021-10-06 19:15:49
【问题描述】:
public interface Page<T> {
  T nextPage();
}

它的实现

public class ConcretePageA implements Page<TypeA> {
  public TypeA nextPage() {
    // do stuff
  }
}

然后我有一个接口消耗Page

public interface Source {
  <T> int getData(Page<T> page)
}

及其实现

public class ConcreteSourceA implements Source {
  public int getData(Page<TypeA> page) {   //error: getData in ConcreteSourceA clashes with getData in Source
    // do stuff
  }
}

我试过了,还是不行

public class ConcreteSourceA implements Source {
  public <TypeA> getData(Page<TypeA> page) { // error: expect com.foo.TypeA but got TypeA
    // do stuff
  }
}

当我执行上述操作时,我得到一个编译错误提示

getData in ConcreteSourceA clashes with getData in Source

我知道我做错了什么,但是如何在仍然有多个使用不同类型的实现的同时修复它?

我是不是一开始就做错了?泛型不是解决此问题的正确方法吗?

【问题讨论】:

    标签: java oop generics


    【解决方案1】:

    看起来你想让SourcePage 一样通用,就像这样:

    public interface Source<T> {
      int getData(Page<T> page);
    }
    

    然后,您可以定义仅实现某些特殊化的实现,例如

    public class ConcreteSourceA implements Source<TypeA> {
      public int getData(Page<TypeA> page) {
        // do stuff
        return 0;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多