繁体   English   中英

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

[英]Writing a method to accept interface type instead of class type

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

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

以下方法声明应该有效 -

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

请注意参数List<XYPlottable>更改为List<? extends XYPlottable> List<? extends XYPlottable> - 这被称为通配符。
在此处阅读有关通用通配符的更多信息

尝试这个:

List<? extends XYPlottable>

在方法声明中。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM