开发者

Inheritance & Lists

Class B extends class A. I have a list of B (List<B> list1), but for some operations I need only class A fields, but List<A> list2 = list1 doesn't work. H开发者_如何学Cow can this problem be solved?


List<? extends A> list2 = list1;

This means "a list of a specific subtype of A".

If you could use List<A>, which means "a list of A an all of its subclasses", you would loose the compile time safety. Imagine:

List<B> list1 = ..;
List<A> list2 = list1;
list2.add(new C());
for (B b : list1) {
    //ClassCastException - cannot cast from C to B
}


Generics are type strict , they don't support co-variant types like array.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜