Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

java - Why do you assign an objects to an interface?

I have heard several times that when instantiating objects you should do:

"Interface" name = new "Class"();

For example for the class linkedlist that implements List:

List<String> name = new LinkedList<String>();

LinkedList implements many interfaces, including queue, deque, etc. What is the difference between the above code and

LinkedList<String> name = new LinkedList<String>();

or

Queue<String> name = new LinkedList<String>();

Why must the type be specified twice as well; it seems redundant but oracledocs don't seem to mention it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

LinkedList<String> name = new LinkedList<String>(); is redundant in Java 7. It can be rewritten to LinkedList<String> name = new LinkedList<>();.

The reason you want to write something similar to:

// Java 7 way:
List<String> name = new LinkedList<>();

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...