Suppose I have an interface
interface Car {
void wroomWroom();
}
And bunch of classes that implement this interface.
class Mercedes implements Car {
// implementation
}
class Volkswagen implements Car {
// Implementation
}
In some place in the code I have two functions
// ...
bool checkCarsGeneric(List<? extends Car> cars) {
System.out.println("Do generic checks");
return true;
}
bool checkCarsByInterface(List<Car> cars) {
System.out.println("Do generic checks");
return true;
}
Both of these functions syntactically correct and, surprisingly, work correctly. In what cases I should prefer List<? extends Car>
syntax over List<Car>
syntax and why?
UPD
Invocation of these functions is follows:
List<Car> cars = Arrays.asList(
new Mercedes(),
new Volkswagen(),
new Mercedes(),
new Volkswagen()
);
checkCarsGeneric(cars);
checkCarsByInterface(cars);