Page 1 of 1

OCPJP 1z0-816

Posted: Sun Aug 11, 2019 11:47 pm
by sreeharshitha
I am preparing for 1z0-816 from Boyarsky/Selikoff book and came across this code. the explanation says lines 7 and 8 do not compile. I cannot understand why it doesn't compile because List<? extends Bird> can accept List<Bird> or List<Sparrow>.

2: static class Sparrow extends Bird{}
3: static class Bird{}
4:
5: public static void main(String... args){
6: List<? extends Bird> birds = new ArrayList<Bird>();
7: birds.add(new Sparrow());
8: birds.add(new Bird());
9: }

Re: OCPJP 1z0-816

Posted: Mon Aug 12, 2019 12:23 am
by admin
On what line does it fail? What is the error message? What do you think is the issue?

Re: OCPJP 1z0-816

Posted: Mon Aug 12, 2019 6:29 pm
by sreeharshitha
the compilation fails on lines 7 and 8. As Sparrow is a subclass of Bird, why can't be Sparrow object put into birds?

Re: OCPJP 1z0-816

Posted: Mon Aug 12, 2019 9:20 pm
by admin
Please go through this write up:
viewtopic.php?f=2&t=473
It explains your doubt.