Inheritance and Lists

Class B extends class A. I have a list B ( List<B> list1)but for some operations I only need fields of class A, but it List<A> list2 = list1doesn’t work. How to solve this problem?

+3
source share
2 answers
List<? extends A> list2 = list1;

This means a list of a specific subtype A.

If you can use List<A>what "list A of all its subclasses" means, you will lose compile-time security. Imagine:

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

Generics are strict; they do not support sharing types such as an array.

+3
source

All Articles