【问题标题】:Implementing generic interface in not generic class在非泛型类中实现泛型接口
【发布时间】:2014-07-10 17:16:43
【问题描述】:

我想在一个类中实现一个通用接口。 考虑实现这个通用接口:

public interface Lookup<T>{
  public T find(String name);
}

这是实现查找的非通用类:

public class IntegerLookup implements Lookup<Integer>{
  private Integer[] values;
  private String[] names;

  public IntegerLookup(String[] names, Integer[] values) {......}
  //now I want to write the implemented method - find

我的问题是: 我需要如何编写这个实现的方法? 我需要覆盖它吗?是吗?

public Object find(String name){...}

会好吗?或:

public Integer find(String name){...}

【问题讨论】:

  • 在超类型中使用T 的任何地方,在使用Integer 作为T 的类型参数的子类中应使用Integer
  • 你为什么不能用@Override注解试试呢?
  • @SotiriosDelimanolis 但它是在超级类型中写的 Object 而不是 T ......或者我错了?
  • 超类型Lookup已将方法的返回类型声明为T
  • 你想要一个实用的方法来查找字符串但根据它的调用方式返回一个灵活的类型吗?

标签: java generics


【解决方案1】:

这里的语法

public class IntegerLookup implements Lookup<Integer>{
//                                           ^

绑定提供的类型参数,即。 Integer,到Lookup声明的类型变量,即。 T.

所以,

public Integer find(String name){...}

这和做的一样

Lookup<Integer> lookup = ...;
lookup.find("something"); // has a return type of Integer

【讨论】:

    【解决方案2】:

    从您的 cmets 看来,您确实想使用 Object 作为返回类型。我无法想象你为什么要这样做,但如果是这样,你实际上需要实现Lookup&lt; Object &gt;,而不是Lookup&lt; Integer &gt;

    但不要那样做。使用Integer 作为返回类型,因为该类型在您的实现中代表T

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 2020-05-14
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多