Why List = new ArrayList() ? in Java

The main reason you’d do this is to decouple your code from a specific implementation of the interface. When you write your code like this:

List list = new ArrayList();  

the rest of your code only knows that data is of type List,  which is preferable because it allows you to switch between different implementations of the List interface with ease.

This is called programming to interface. This will be helpful in case if you wish to move to some other implementation of List in the future.

If you want some methods in ArrayList then you would need to program to the implementation

i.e. ArrayList a = new ArrayList()

 

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.