Let’s say you have:
public interface A {}
public class B implements A {}
public class C {
void foo (List<A>) {}
}
public class Test {
//Declaration one
List<A> x = new List<A>();
//Declaration two
List<A> x = new List<B>();
B b = new B();
x.add(b);
new C().foo(x);
}
Now obviously declaration one is the correct way to do this, and you receive a compile error on declaration two. I would like to know though why Java chooses to enforce type safety in this specific manner; if a list of Cats is still a list of Animals, why does a method expecting a list of animals balk at receiving a bunch of cats?
Curiousity, more than anything else – and a chance to better refine my knowledge.
Cheers,
Dave.
Java generics are not covariant. If you could do this:
then you would be able to do:
which violates the concept that an
ArrayList<Cat>can only holdCatobjects (or subclass objects).Read this for for more details: Java theory and practice: Generics gotchas.