编写一个方法来接受接口类型而不是类类型

时间:2011-04-24 15:16:41

标签: java generics interface

我正在尝试创建一些实现特定接口的类(在本例中为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>

我希望我只是有一点时间而且遗漏了一些非常明显的东西,但也许我对如何使用界面有误解。

3 个答案:

答案 0 :(得分:21)

如下所示的方法声明应该有效 -

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

请注意参数List<XYPlottable>中的更改为List<? extends XYPlottable> - 这称为通配符。
阅读有关通用通配符here

的更多信息

答案 1 :(得分:7)

试试这个:

List<? extends XYPlottable>

在方法声明中。

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

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

答案 2 :(得分:0)

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

的列表
List<XYPlottable> value = _controller.getValues(tripName)
相关问题