I'm bussy with OCP and Chapter 3 there Upper-Bounded Wildcards.
There is an example like:
But what is Number?
What kind of objects can I add to this list?
It is compiling, it running...
The method they give in the book:
Or is this a mistake in the book (typo) in the declaration? (is not mentioned in the studyguide as a mistake)
I'm asking this, because the declaration is with "List<? extends Number>" and not as 'norma'l with "List<Integer>", see example Tutorialspoint below.
I have found this on Tutoiralspoint:
But I can follow this how this works but what is Number? Number does not exist in Java as far as I remember. Is not declared anywhere. I know/understand that the ? wil be converted to Object (tyep erasue)
Number is the superclass of all numeric primitive wrapper types in Java, and also BigInteger and BigDecimal.
Nico van de Kamp wrote:What kind of objects can I add to this list?
None. You can't add anything to a container using a variable that is declared with an upper bound. You can only get things out of it. The reason for this is that since you don't know what the exact type of the container is (this is what the question mark means), the compiler prevents you from adding integers to an object that at runtime turns out to be a container of doubles.
The super keyword does the inverse: You can add any kind of number to such a container, but you can't get any numbers out of it:
The mnemonic PECS is often used to remember this: Produces: extends; Consumer: super.
In your total() method, list is a producer of Number and is thus declared as List<? extends Number>.
In my fill() method, list is a consumer of Number and is thus declared as List<? super Number>.