When to use extends and super
Wildcards are most useful in method parameters. They allow for the necessary flexibility in method interfaces.
People are often confused when to use extends and when to use super bounds. The rule of thumb is the get-put principle. If you get something from a parametrized container, use extends.
int totalFuel(List extends Vehicle> list) {
int total = 0;
for(Vehicle v : list) {
total += v.getFuel();
}
return total;}
The method totalFuel gets Vehicles from the list, asks them about how much fuel they have, and computes the total.
If you put objects into a parameterized container, use super.
int totalValue(Valuer super Vehicle> valuer) {
int total = 0;
for(Vehicle v : vehicles) {
total += valuer.evaluate(v);
}
return total;}
The method totalValue puts Vehicles into the Valuer.
It's useful to know that extends bound is much more common than super.