为什么要首选Java类的接口? [英] Why should the interface for a Java class be preferred?

查看:262
本文介绍了为什么要首选Java类的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PMD 会报告违规行为:

ArrayList<Object> list = new ArrayList<Object>();

违规是避免使用像'ArrayList'这样的实现类型;而是使用界面。

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>();

为什么后者使用 List ?代替 ArrayList

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.

在编写自己的API时,遵循这种做法甚至是个好主意。如果你这样做,你会发现以后会更容易将单元测试添加到你的代码中(使用模拟技术),并在将来需要时更改底层实现。

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.

希望有所帮助!

这篇关于为什么要首选Java类的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆