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

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

    @Bhushan answered why. To answer your confusion Why nobody uses

    CharSequence s = new String("String");
    

    or

    OutputStream out = new PrintStream(OutputStream);
    

    CharSequence contains only few common methods. Other classes that implement this interface are mostly buffers and only String is immutable. CharSequence defines common api for classes backed by char array and This interface does not refine the general contracts of the equals and hashCode methods (see javadoc).

    OutputStream is low-level api for writing data. Because PrintStream adds extra convenient methods for writing - higher level of abstraction, it's used over OutputStream.

提交回复
热议问题