Java优良作法-接口类型的声明,而不是实现类型的声明 [英] Java good practice - Declarations of interface types instead of declarations of implementation types

查看:81
本文介绍了Java优良作法-接口类型的声明,而不是实现类型的声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 O'Reilly-Android编程中,建议您避免使用以下代码:

In "O'Reilly - Programming Android" they recommend avoiding this code:

ArrayList<String> a = new ArrayList<String>();

但要替换为:

List<String> a = new ArrayList<String>();

他们认为,如果以后使用 a类型,则维护代码会更容易应该更改为说一个链表。如果是这样,为什么不将其设置为 Collection 类型,甚至是 Object 类型?

They argue it's easier to maintain code if later the type of a should be changed to say a linked list. If so, why not make it of type Collection, or even Object?

我认为由于必须更改实例化以更改其类型,因此,最好将其类型限制为更多,并在需要时更改多余的行。

I feel that as the instantiation must be changed to change its type, surely it's better to keep it type restricted as much as possible and change the extra line if needed.

它们正确吗?

推荐答案

在我个人看来,您应该使用(在层次结构中)

In my personal opinion you should use the interface as high (in hierarchy) as possible and have the operations you will need.

在某些情况下,您只需要存储对象,进行迭代并使用索引获取它们即可。 列表接口提供了该功能。对象不为您提供这些方法。

In some cases you need just to store objects, iterate, and get them using index. List interface is providing that. Object does not provide you with these methods.

使用 Object -您将使代码的可读性降低,并且可能被强制转换为例外。

Using Object - you will make your code less readable and there could be cast exceptions.

这篇关于Java优良作法-接口类型的声明,而不是实现类型的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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