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

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

    The reason behind this is not technical but the stuff you have to read between the lines of code: The List and Map examples says: "I'm only interested in basic list/map stuff, basically you can use anything here." An extreme example of that would be

    Iterable items = new ArrayList();
    

    when you really only want to do some stuff for each thing.

    As an added bonus this makes it a little easier to refactor the code later into common utility classes/methods where the concrete type is not required. Or do you want to code your algorithm multiple times for each kind of collection?

    The String example on the other hand is not seen wildly, because a) String is special class in Java - each "foo" literal is automatically a String and sooner or later you have to give the characters to some method which only accepts String and b) the CharSequence is really ahh minimal. It does not even support Unicode beyond the BMP properly and it misses most query/manipulation methods of String.

提交回复
热议问题