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

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

    This (good) style of declaring the type as the Interface the class implements is important because it forces us to use methods only defined in the Interface.

    As a result, when we need to change our class implementations (i.e. we find our ArraySet is better than the standard HashSet) we are guaranteed that if we change the class our code will work because both classes implement the strictly-enforced Interface.

提交回复
热议问题