0

I have two classes parent and child and child extends parent.

Parent parent = new Child();

Works as expected but the confusion happens when the object is in an container like so.

Vector<Parent> vp = new Vector<Child>();

This gives the error:

incompatible types: Vector<Child> cannot be converted to Vector<Parent>

So my question is does the container prevent the implicit typecasting that occurs when we do

parent = new Child();
David Soroko
  • 8,521
  • 2
  • 39
  • 51
  • Worth a read: [1](https://stackoverflow.com/questions/18666710/why-are-arrays-covariant-but-generics-are-invariant) [2](https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po) – TiiJ7 Mar 08 '19 at 10:39

1 Answers1

0

It looks like you expect that given Child subclass of Parent, Vector<Child> is a subclass of Vector<Parent>. This behavior is called covariance (things vary together) and it is not the way things work in Java's generic collections. In Java Vector<Child> and Vector<Parent> are not related (they have an invariant relationship).

A more detailed explanation here: Covariance, Invariance and Contravariance explained in plain English?

David Soroko
  • 8,521
  • 2
  • 39
  • 51