Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

collections - 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...