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

前端 未结 4 1528
逝去的感伤
逝去的感伤 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:57

    Such code doesn't use the List class, it declares the variable as being of type List. This is called abstraction

    List is an interface, which defines what methods the actual class has, without specifying which actual class is used.

    Although not a big deal here, this practice can be very important, even essential in more complexes situations. It's good practice to always follow this pattern.

提交回复
热议问题