This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Originally posted by John Landon: Given the facts that: 1. getSub1 returns collection of Sub1 that extends Sub class. 2. getSub2 returns collection of Sub2 that extends Sub class.
Why do I get a compilation error on the last line of the code?
The declaration "Collection<? extends Sub> sub" does *not* mean a collection that takes anything that extends the Sub class type. It means a collection of some unknown class type that extends the Sub class type.
Since the class type is unknown, it can be any type that extends the Sub class type... and, it is impossible to add anything to the collection, as you can't confirm the type to match.
The rules: - with "? super X" you can add anything that IS-A X but can only retrieve as Object without casts - with "? extends X" you can add nothing but can retrieve as X without casts - with "X" you can add anything that IS-A X and retrieve as X without casts