According to Java Polymorphism feature
your subclass object can be assigned to a reference type of Parent class.
Here it is assigning subclass to a reference of type ParentClass.
That is why its working
Hi,
[This] (What is PECS (Producer Extends Consumer Super)?) should really help you understand. There is a rule called PECS. Producer extends and consumer super. This rule should have been included in Java tutorial of wildcards because without this, the understanding of Bounded wildcards seemed incomplete to me.
It is essentially implying, that if you want to read only from a List (not write into it) , then use
List<? extends ParentClass>
it indicates that you will get objects which are subtypes of ParentClass or ParentClass. Also, implies that List is in read only mode.
And if you want to 'put' into a list not read from it, then by declaring your list as
List<? Super ParentClass>
you can add types that are either ParentClass or its types. But nothing else can be put in.
Also, wrote the following code and
1 List<? super ChildClass > list1 = new ArrayList<ChildClass>();
2 list1.add(new GrandChildAbstract());
3 list1.add(new ChildClass());
4 list1.add(new Abstractclass());
5
6 ChildClass ch= list1.get(0);
7 Abstractclass ch = list1.get(0);
8
9 List<? extends ChildClass> list2 = new ArrayList<ChildClass>();
10 list2.add(new GrandChildAbstract());
11 list2.add(new ChildClass());
12 list2.add(new Abstractclass());
And Eclipse compile time errored out line # 4, 6, 7 and 10, 11, 12.
This clearly indicates that super bound wildcards must be understood in context of read only and write only context.