Why is it not possible to call List not with List even if Integer extends Number?

后端 未结 2 1204

I was wondering why is it not possible to call List not with List> even Integer is an extended class of the abstract class

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 06:57

    Because you could e.g. add an instance of a different subclass of Number to List, e.g., an object of type Double, but obviously you shouldn't be allowed to add them to List:

    public void myMethod(List list) {
        list.add(new Double(5.5));
    }
    

    If you were allowed to call myMethod with an instance of List this would result in a type clash when add is called.

提交回复
热议问题