开发者

Java Type Casting Problem [duplicate]

开发者 https://www.devze.com 2023-03-08 20:46 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: How to Cast a Vector<ObjectA&g开发者_JAVA百科t; to Vector<ObjectB> in Java?
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

How to Cast a Vector<ObjectA&g开发者_JAVA百科t; to Vector<ObjectB> in Java?

Is List&lt;Dog&gt; a subclass of List&lt;Animal&gt;? 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!

0

精彩评论

暂无评论...
验证码 换一张
取 消