artem
artem

Reputation: 16777

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. How can this problem be solved?

Upvotes: 3

Views: 122

Answers (2)

Bozho
Bozho

Reputation: 597234

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
}

Upvotes: 4

Jigar Joshi
Jigar Joshi

Reputation: 240928

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

Upvotes: 3

Related Questions