Why should the interface for a Java class be preferred?

后端 未结 10 1347
陌清茗
陌清茗 2020-11-22 05:43

PMD would report a violation for:

ArrayList list = new ArrayList();


The violation was \"Avoid using implementat

10条回答
  •  心在旅途
    2020-11-22 06:16

    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!

提交回复
热议问题