I have classes A, B, C and D where B extends A, C extends A and
Did I use the
extends A>correctly?
List extends A> list; means that the 'list' refers to an object implemented interface List, and the list can hold elements inherited from class A (including A). In other words the following statements are correct:
List extends A> listA1 = new ArrayList();
List extends A> listB1 = new ArrayList();
List extends A> listC1 = new ArrayList();
List extends A> listD1 = new ArrayList();
Java generics are a compile-time strong type checking. The compiler uses generics to make sure that your code doesn't add the wrong objects into a collection.
You tried to add C in ArrayList
listB1.add(new C());
If it were allowed the object ArrayList would contain different object types (B,C).
That is why the reference listB1 works in 'read-only' mode. Additionally you could take a look at this answer.
how to resolve this?
List list = new ArrayList();