将对象声明为接口有什么好处? [英] What are the benefits of declaring an object as interface?

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

问题描述


可能重复:

对于界面编程是什么意思&nd ;;

我注意到有些人喜欢将对象声明为它实现的接口之一,即使在变量范围内,也没有必要将其视为界面,例如没有期望接口的外部API。

I noticed that some people like to declare an object as one of the interfaces it implements even though, within the scope of the variable, it is not necessary to look at it as the interface, e.g. there is no external API that expect an interface.

例如:

Map<String, Object> someMap = new HashMap<String, Object>();

或者你可以做到

HashMap<String, Object> someMap = new HashMap<String, Object>();

并避免导入 java.util.Map 完全。

通过接口(上面第一个)而不是类本身(上面第二个)声明它有什么好处?

What are the advantages of declaring it through an interface (first above) as opposed to the class itself (second above)?

谢谢

推荐答案

如果以后没有使用该变量,则没有优势/劣势。您使用接口而不是对象的原因是允许更大的灵活性,但如果不使用该变量,则与性能持续存在差异。

If the variable is not used later, there is no advantage/disadvantage. The reason you would use an interface rather than an object is to allow for more flexibility, but if that variable isn't used, there is no difference from a performance persepective.

这篇关于将对象声明为接口有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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