I was wondering why is it not possible to call List
not with List
Because you could e.g. add an instance of a different subclass of Number
to List<Number>
, e.g., an object of type Double
, but obviously you shouldn't be allowed to add them to List<Integer>
:
public void myMethod(List<Number> list) {
list.add(new Double(5.5));
}
If you were allowed to call myMethod
with an instance of List<Integer>
this would result in a type clash when add
is called.
Generics are not co-varient like arrays. This is not allowed because of type erasure.
Consider classes Vehicle
, Bike
and Car
.
If you make
public void addVehicle(List<Vehicle> vehicles){
vehicles.add(new Car());
}
Car
is of type Vehicle
, you can add a
Car
into Vehicle
because it passes IS-A test.List<Bike>
to addVehicle(List<Vehicle> vehicles)
? you would have added a Car
to bike list. which is plain wrong. So generics doesn't allow this.
Read about Polymorphism with generics