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
?
Spring framework applies the concept of interfaces really nicely - http://www.springframework.org/
Spring supplies the implementation to a concrete class via configuration file and so the concrete class need not know anything at all about the implementation.
Study of Spring exemplifies the advantages of Interface based programming in Java.
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.
Even for local variables, using the interface over the concrete class helps. You may end up calling a method that is outside the interface and then it is difficult to change the implementation of the List if necessary. Also, it is best to use the least specific class or interface in a declaration. If element order does not matter, use a Collection instead of a List. That gives your code the maximum flexibility.
It's a good practice : Program to interface rather than implementation
By replacing
ArrayList
withList
, you can changeList
implementation in future as below depending on your business use case.OR
OR
OR
some other
List
specific implementation.List
interface defines contract and specific implementation ofList
can be changed. In this way, interface and implementation are loosely coupled.Related SE question:
What does it mean to "program to an interface"?
Properties of your classes/interfaces should be exposed through interfaces because it gives your classes a contract of behavior to use, regardless of the implementation.
However...
In local variable declarations, it makes little sense to do this:
If its a local variable, just use the type. It is still implicitly upcastable to its appropriate interface, and your methods should hopefully accept the interface types for its arguments, but for local variables, it makes total sense to use the implementation type as a container, just in case you do need the implementation-specific functionality.