Can someone please explain to me difference between extends and super in java generics with wildcards?
I have read related posts and didn't get complete understanding. If you could explain me with real time example that would be great help for me.
what does PECS(producer you extend, consumes you use super) mean?
The type parameter <? extends T> means T or any subclass of T.
The type parameter <? super T> means T or any superclass of T.
For example:
In Effective Java, Joshua Bloch recommends the mnemonic PECS -- for "Producer-Extends, Consumer-Super".
"If a parameterized type represents a T producer, use
<? extends T>
; if it represents a T consumer, use<? super T>
."
This is also known as the Get and Put Principle, from Java Generics by Maurice Naftalin and Philip Wadler.
"Use an
extends
wildcard when you only get values out of a structure, use asuper
wildcard when you only put values into a structure, and don't use a wildcard when you both get and put."