Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 553
jnancheta Avatar asked Sep 29 '08 04:09

jnancheta


People also ask

Why should I use interface in Java?

In Java, an interface specifies the behavior of a class by providing an abstract type. As one of Java's core concepts, abstraction, polymorphism, and multiple inheritance are supported through this technology. Interfaces are used in Java to achieve abstraction.

Why interfaces are preferred over abstract classes Java?

Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Interfaces are a good choice when we think that the API will not change for a while.

What is the importance of the interface of a class of objects?

Interfaces are useful for the following: Capturing similarities among unrelated classes without artificially forcing a class relationship. Declaring methods that one or more classes are expected to implement. Revealing an object's programming interface without revealing its class.


2 Answers

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!

like image 102
kolrie Avatar answered Oct 19 '22 23:10

kolrie


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.

like image 20
AdamC Avatar answered Oct 20 '22 00:10

AdamC