pse*_*ble 11 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
...
}
Run Code Online (Sandbox Code Playgroud)
这很好用.我还有一种方法可以尝试绘制XYPlottable的任何东西:
public static Frame createPlot(String title, String xAxisLabel, String yAxisLabel,
List<XYPlottable> points, boolean fitLine) {
Run Code Online (Sandbox Code Playgroud)
所以我尝试使用上面的一个具体类,它抱怨有不兼容的类型:
List<A> values = _controller.getValues(tripName);
XYPlotter.createPlot("Plot A", "B", "C", values, false);
Run Code Online (Sandbox Code Playgroud)
这是确切的错误:
incompatible types
required: java.util.List<XYPlottable>
found: java.util.List<A>
Run Code Online (Sandbox Code Playgroud)
我希望我只是有一个时刻,并且遗漏了一些非常明显的东西,但也许我对如何使用接口有误解.
Pre*_*raj 21
以下方法声明应该有效 -
public static Frame createPlot(String title, String xAxisLabel, String yAxisLabel,
List<? extends XYPlottable> points, boolean fitLine) {
Run Code Online (Sandbox Code Playgroud)
请注意参数更改List<XYPlottable>为List<? extends XYPlottable>- 这称为通配符.在此处
阅读有关通用通配符的更多信息
试试这个:
List<? extends XYPlottable>
Run Code Online (Sandbox Code Playgroud)
在方法声明中.
Java中的泛型可能令人困惑.
http://download.oracle.com/javase/tutorial/java/generics/index.html