Search code examples
javacollectionsinterface

Why should the interface for a Java class be preferred?


PMD would report a violation for:

ArrayList<Object> list = new ArrayList<Object>();

The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".

The following line would correct the violation:

List<Object> list = new ArrayList<Object>();

Why should the latter with List be used instead of ArrayList?


Solution

  • Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code.

    It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implementation if needed in the future.

    Here's a good article on the subject.

    Hope it helps!