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

前端 未结 12 947
轻奢々
轻奢々 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:40

    For

    List ints = new ArrayList();
    Map map = new HashMap();
    

    List and Map are the interfaces, so any class implementing those interfaces can be assigned to these references.

    ArrayList is one of the several classes (another is LinkedList) which implement List interface.

    Same with Map. HashMap, LinkedHashMap, TreeMap all implement Map.

    It is a general principle To program for interfaces and not for implementations. Due to this, the programming task becomes easier. You can dynamically change the behavior of the references.

    If you write

    ArrayList ints = new ArrayList();
    HashMap map = new HashMap();
    

    ints and map will be ArrayList and HashMap only, forever.

提交回复
热议问题