I have a strange problem with inheritance and I don't understand why it should not work:
public interface A { }
public interface B extends A {}
public class C {
void test() {
ArrayList<A> foo = new ArrayList<B>();
}
}
But compiling gives me the following error
Type mismatch: cannot convert from ArrayList<B> to ArrayList<A> C.java /bla/src/de/plai/test line 8 Java Problem
It may seem counterintuitive at first, but even if class B is a subclass of A, a List<B> is not a subclass of List<A>. I gave a more detailed explanation and example in this earlier answer to a similar post. See also this other answer for a link to the respective item in Effective Java 2nd Edition.
The solution to this problem is using wildcards. Thus you should declare your list as
List<? extends A> foo = new ArrayList<B>();
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