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.
Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).
Yes, you can define an interface inside a class and it is known as a nested interface. You can't access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.
You should use an interface if you want a contract on some behavior or functionality. You should not use an interface if you need to write the same code for the interface methods. In this case, you should use an abstract class, define the method once, and reuse it as needed.
In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With