Possible Duplicates:
How to Cast a Vector<ObjectA&g开发者_JAVA百科t; to Vector<ObjectB> in Java? IsList<Dog>
a subclass ofList<Animal>
? Why aren't Java's generics implicitly polymorphic?
I've a logical problem with the java type casting.
I have a class A which extends class B and therefore I can have a statement like
A a = new B();
but why I get a compiler error for Vector<A> va = new Vector<B>();
or Vector<A> va = (Vector<A>)new Vector<B>();
java generics don't support co-variance, so Vector<B>
does NOT extend Vector<A>
Think of it like this;
If C
also extends B
then you could put C
into Vector<B>
.
Now if you could cast it to a Vector<A>
and you did a get
you would get an instance of C
!
That wouldn't make much sense so the compiler doesn't allow it. As @amit says Co-variance is the name for this.
See this posting
The type of the variable must match the type you pass to the actual object type.
When it comes to polymorphism with regards to generic type, java does not allow you to as follows:
class A { }
class B extends A { }
List<A> myList = new ArrayList<B>();
This is because on compilation, the compiler gets rid of generic typing (through something called type erasure) and does was it used to do in pre java 5 code. This is confusing because it is not the same behavior with arrays. With arrays you can do:
A[] myArr = new B[10];
But such is not the case with generics. Again, when it comes to generics the type of the variable must match the type you pass to the actual object type.
Hope that helps!
精彩评论