java - Generics and Inheritence? -
this question has answer here:
public static void main(string... args) { list<child> list1 = new arraylist<child>(); method2(list1); } public static void method2(list<parent> list1) { }
i below compilation error
the method method2(list) undefined ...
above issue can solved modifying list<parent> list1
list<? extends parent> list1
.
but if try add child object below
public static void method2(list<? extends parent> list1) { child child1 = new child(); list1.add(child1); }
it gives compilation error again
the method add(capture#1-of ? extends parent) in type list not applicable arguments (child)
so question if list<child>
can passed parameter list<? extends parent> list1
why can't add child object under list<? extends parent>
?
this common misunderstanding. fact child extends parent not make list<child>
extend list<parent>
. sounds unintuitive in cases one, there is. java tutorial:
given 2 concrete types , b (for example, number , integer), myclass< a> has no relationship myclass< b>, regardless of whether or not , b related. common parent of myclass , myclass object.
read this details.
as adding list, short answer is: imagine have class child2 extends parent
, now, list receiving parameter @ method2(list<? extends parent> list1)
either list<child1>
or list<child2>
. thus, given second case possible, adding child1 object not type safe.
now, fact can't add not mean can't other useful stuff, getting size, etc.
Comments
Post a Comment