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 ?


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!


This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.


In general I agree that decoupling interface from implementation is a good thing and will make your code easier to maintain.

There are, however, exceptions that you must consider. Accessing objects through interfaces adds an additional layer of indirection that will make your code slower.

For interest I ran an experiment that generated ten billion sequential accesses to a 1 million length ArrayList. On my 2.4Ghz MacBook, accessing the ArrayList through a List interface took 2.10 seconds on average, when declaring it of type ArrayList it took on average 1.67 seconds.

If you are working with large lists, deep inside an inner loop or frequently called function, then this is something to consider.

链接地址: http://www.djcxy.com/p/57286.html

上一篇: 战略模式的实例

下一篇: 为什么要选择Java类的接口?