Reputation: 2561
I am trying to create some classes that implement a particular interface (in this case, XYPlottable
) and a method that can handle any class implementing that interface.
So far I have the following (that works):
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
...
}
This works fine. I also have a method to try and plot anything that's XYPlottable:
public static Frame createPlot(String title, String xAxisLabel, String yAxisLabel,
List<XYPlottable> points, boolean fitLine) {
So I attempt to go use it with one of the above concrete classes and it complains about having incompatible types:
List<A> values = _controller.getValues(tripName);
XYPlotter.createPlot("Plot A", "B", "C", values, false);
Here's the exact error:
incompatible types
required: java.util.List<XYPlottable>
found: java.util.List<A>
I hoping I'm just having a moment and missing something really obvious, but maybe I'm having a misunderstanding of how I should be using interfaces.
Upvotes: 11
Views: 5210
Reputation: 7139
You are using the concrete type A
in your list of values. This should be a list of XYPlottables
e.g
List<XYPlottable> value = _controller.getValues(tripName)
Upvotes: 0
Reputation: 308753
Try this:
List<? extends XYPlottable>
in the method declaration.
Generics in Java can be confusing.
http://download.oracle.com/javase/tutorial/java/generics/index.html
Upvotes: 8
Reputation: 7902
Method declaration like following should work -
public static Frame createPlot(String title, String xAxisLabel, String yAxisLabel,
List<? extends XYPlottable> points, boolean fitLine) {
Note the change in the parameter List<XYPlottable>
to List<? extends XYPlottable>
- This is called as wildcards.
Read more about generic wildcards here
Upvotes: 22