I am learning about interfaces in Java and one example they give is being able to create a linked list using the List interface List<String> strings = new LinkedList<>();
but they don't go into any detail. Why would I want to do this as oppose to LinkedList<String> strings = new LinkedList<>();
?

- 453
- 6
- 19
-
`List
` is an interface while `LinkedList – Vishwa Ratna Aug 27 '20 at 03:50`is not. -
Look for Polymorphism in java. https://www.javatpoint.com/runtime-polymorphism-in-java. – Soheil Rahsaz Aug 27 '20 at 03:54
-
See [Liskov substitution principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle). – Bohemian Aug 27 '20 at 04:46
3 Answers
List<T>
is an interface, meaning there are a certain number of methods that you must implement when you extend List
. LinkedList
happens to extend List
. When you do List<String> strings = new LinkedList<>();
, java only sees List
's methods. However, when you do LinkedList<String> strings = new LinkedList<>();
java sees it as a LinkedList
and it will work when you call methods LinkedList
has like getLast
. People do List<String> strings = new LinkedList<>();
mainly for readability but it should be about the same.

- 1,175
- 1
- 13
- 25
For local variables, it doesn't matter all that much, at least not in this case.
The main benefit of List<String> strings = new LinkedList<>();
is that you could simply swap the LinkedList for an ArrayList or any other List implementation if needed.
This is most important at the "edges" of your class (parameters, return types, fields) because it makes your API more flexible for two reasons:
- Other classes are not bound by your choice of List implementation, because your class will take any List
- Other classes that interface with your class are forcibly unaware of your class' internal choice of which List implementation to use, which means you can switch from an ArrayList to a LinkedList or vice versa at any time, without breaking code outside of your class
From Effective Java, 3rd Edition, Item 64: REFER TO OBJECTS BY THEIR INTERFACES
If you get into the habit of using interfaces as types, your program will be much more flexible. If you decide that you want to switch implementations, all you have to do is change the class name in the constructor (or use a different static factory).
So, with List<String> strings = new LinkedList<>();
, you just have to change the implementation name and the rest of the client code remains same.
With LinkedList<String> strings = new LinkedList<>();
, you may have to modify your client code.
Note that it's entirely appropriate to go ahead with implementation class as types. But, if you can use an interface as type, it's the best choice.

- 1,393
- 1
- 8
- 16