【问题标题】:Writing a method to accept interface type instead of class type编写一个方法来接受接口类型而不是类类型
【发布时间】:2011-04-24 23:42:49
【问题描述】:

我正在尝试创建一些实现特定接口的类(在本例中为XYPlottable)和一个可以处理实现该接口的任何类的方法。

到目前为止,我有以下(有效):

public interface XYPlottable {
    public Number getXCoordinate();
    public Number getYCoordinate();
    public Number getCoordinate(String fieldName);
}

public class A implements XYPlottable {
//Implements the above interface properly
...
}

public class B implements XYPlottable {
//Implements the above interface properly
...
}

这很好用。我还有一种方法可以尝试绘制 XYPlottable 的任何内容:

public static Frame createPlot(String title, String xAxisLabel, String yAxisLabel,
                               List<XYPlottable> points, boolean fitLine) {

所以我尝试将它与上述具体类之一一起使用,但它抱怨类型不兼容:

List<A> values = _controller.getValues(tripName);
XYPlotter.createPlot("Plot A", "B", "C", values, false);

这是确切的错误:

incompatible types
  required: java.util.List<XYPlottable>
  found:    java.util.List<A>

我希望我只是有一点时间并错过了一些非常明显的东西,但也许我对应该如何使用接口有误解。

【问题讨论】:

    标签: java generics interface


    【解决方案1】:

    下面的方法声明应该可以工作 -

    public static Frame createPlot(String title, String xAxisLabel, String yAxisLabel,
                                   List<? extends XYPlottable> points, boolean fitLine) {
    

    注意参数List&lt;XYPlottable&gt;List&lt;? extends XYPlottable&gt; 的变化 - 这称为通配符。
    阅读更多关于通用通配符here

    【讨论】:

    • 在这种情况下是否需要泛型,或者您可以只使用接口(XYPlottable)作为列表类型吗?
    • @Strawberry - 这是完全不同的问题 :) .. 你想发布吗?会得到很好的答案;)
    • 酷。这似乎工作得很好。我有点困惑,为什么不能直接使用接口类型本身,但这一定意味着我必须阅读更多关于泛型的内容,因为我的基本理解似乎已经不够了。
    • @Doug Swain - 泛型有点令人困惑。This 是一个非常好的开始链接。
    • 发布了一个关于使用直接接口与通用通配符接口here的问题。
    【解决方案2】:

    试试这个:

    List<? extends XYPlottable>
    

    在方法声明中。

    Java 中的泛型可能会令人困惑。

    http://download.oracle.com/javase/tutorial/java/generics/index.html

    【讨论】:

      【解决方案3】:

      您在值列表中使用具体类型A。这应该是XYPlottables 的列表,例如

      List<XYPlottable> value = _controller.getValues(tripName)
      

      【讨论】:

      • 我之前试过这个,但没有用。我相信原因是因为 _controller 对象实例的方法返回了一个具体类型的 List,所以它不会自动转换。
      • 哦,好吧。我会把我的无用答案留给其他人看:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2016-01-06
      • 2011-03-23
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多