Why are variables declared with their interface name in Java? [duplicate]

When you read

List<String> list = new ArrayList<String>();

you get the idea that all you care about is being a List<String> and you put less emphasis on the actual implementation. Also, you restrict yourself to members declared by List<String> and not the particular implementation. You don’t care if your data is stored in a linear array or some fancy data structure, as long as it looks like a List<String>.

On the other hand, reading the second line gives you the idea that the code cares about the variable being ArrayList<String>. By writing this, you are implicitly saying (to future readers) that you shouldn’t blindly change actual object type because the rest of the code relies on the fact that it is really an ArrayList<String>.

Leave a Comment