Why do some people use the List base class to instantiate a new ArrayList?

前端 未结 4 1531
逝去的感伤
逝去的感伤 2020-12-06 17:36

I keep coming across code where people instantiate a new ArrayList and assign it to the List interface, like this:

List names = new ArrayList&l         


        
4条回答
  •  臣服心动
    2020-12-06 17:54

    To decouple your code from a specific implementation of the interface.

    This also helps you to move to another implementation of the List interface in the future.

    For example -

    You have List names = new ArrayList(); later on you decide that you should have used some other implementation of the List interface, say LinkedList so you would just change it to List names = new LinkedList(); and nothing breaks.

提交回复
热议问题