I have an interface defining a method like this :
public List<IA> myMethod();
with IA another interface.
In my implementation of the method I declare :
public List<A> myMethod() { /* Do something */ }
with A a class implementing IA.
However, Java (or eclipse) doesn’t like it and forces me to have List<IA> in my implementation of myMethod. As A implements IA, I don’t see why this casts an error.
So here are the questions :
- Why do I have this error ?
- Which is the best way to avoid it (knowing I do not have much liberty on the code) ?
You have this error because it’s unsafe from a type-safety point of view. Consider:
Do you really want to be able to add an
Appleto anArrayList<Banana>?You can fix this by changing the declaration to
That will prevent calls from adding to the list (or setting values on it).
If you can’t change the interface, you will have to return a
List<IA>from your method, I’m afraid.See the Java Generics FAQ for much more information.