为什么要将对象分配给接口?
我多次听说过在实例化对象时应该这样做:
I have heard several times that when instantiating objects you should do:
接口name = newClass();
"Interface" name = new "Class"();
例如,实现 List
的类链表:
List<String> name = new LinkedList<String>();
LinkedList
实现了许多接口,包括队列, deque等。以上代码和
LinkedList
implements many interfaces, including queue, deque, etc. What is the difference between the above code and
LinkedList<String> name = new LinkedList<String>();
或
Queue<String> name = new LinkedList<String>();
为什么必须两次指定类型;这似乎是多余的,但oracledocs似乎并未提及它。
Why must the type be specified twice as well; it seems redundant but oracledocs don't seem to mention it.
LinkedList< String> name = new LinkedList< String>();
在Java 7中是多余的。它可以重写为 LinkedList< String> name = new LinkedList<>();
。
LinkedList<String> name = new LinkedList<String>();
is redundant in Java 7. It can be rewritten to LinkedList<String> name = new LinkedList<>();
.
你想写类似的东西:
// Java 7 way:
List<String> name = new LinkedList<>();
是为了让您在以后更改数据收集的自由,如果您改变主意。您的代码以这种方式更加灵活。您应该注意的是,您可以使用的方法仅限于左侧类型(在这种情况下 List
)。这意味着如果您使用层次结构中较高的类型( Object
是极端示例),则可能无法获得所需的所有功能。
is to provide you with the freedom of changing your data collection later, if you change your mind. Your code is much more flexible this way. What you should note about this, is that the methods you are able to use are limited to the left-hand side type (List
in this case). This means that you may not get all the functionality you want, if you use a type that is higher in the hierarchy (Object
being the extreme example).