Why do we first declare subtypes as their supertype before we instantiate them?

前端 未结 12 966
轻奢々
轻奢々 2021-02-01 19:27

Reading other people\'s code, I\'ve seen a lot of:

List ints = new ArrayList();
Map map = new HashMap();
12条回答
  •  死守一世寂寞
    2021-02-01 19:57

     List ints = new ArrayList();
    

    If you write some code that deals only with List then it will work for any class that implements List (e.g. LinkedList, etc). But, if your code directly deals with ArrayList then it's limited to ArrayList.

    CharSequence s = new String("String");
    

    Manually instantiating a String object is not good. You should use string literal instead. I am just guessing the reason that you don't see CharSequence might because it's quite new and also, strings are immutable.

提交回复
热议问题