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()

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s