Java接口作为引用类型? [英] Java interface as reference type?
问题描述
我应该在哪里使用interface作为变量类型?我看到很多人都说最好这样做,但每个例子都指的是集合:
Where should I use interface as variable type? I see a lot of people say it's best practice to do so, but every example refers to collections:
List<String> list = new ArrayList<>()
这种做法主要适用于集合吗?
我从来没有看到任何人在声明i / o流时使用接口。
Does this practice apply mostly to collections? I never saw anyone use interface when declaring i/o streams for example.
推荐答案
这个想法是你想要的隐藏实际的实现,如果它不重要。这通常使代码更简单,并避免意外使用特定于实现的功能。
The idea is that you want to hide the actual implementation if it isn't important. This typically makes the code simpler and avoids accidentially using a implementation specific feature.
因此,只使用 ArrayList
新
。在其他地方使用列表
。 (除非你有充分的理由)
So therefore only use ArrayList
with a new
. Use List
everywhere else. (Unless you have good reason to)
注意:对于Java 10,你可以使用 var
语法来表示局部变量:
Note: For Java 10 you can use the var
syntax for local variables:
var list = new ArrayList<String>();
这篇关于Java接口作为引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!