0

Often I see on many websites that while working with collections in Java, tutors write the code as:

List al = new ArrayList();
List li = new LinkedList();

instead of

ArrayList al = new ArrayList();
LinkedList li = new LinkedList();

Is there any specific reason why it is written that way? Does it have any advantages over the ones written below?

Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71
  • http://stackoverflow.com/a/383982/829571 – assylias Mar 26 '15 at 12:33
  • instand of "What is the reason behind creating objects of sub-class using its super-class while using collections?" you should write "What is the reason behind creating object with reference to Interface while using collections?" – Keval Mar 26 '15 at 13:05

1 Answers1

4

The advantage of declaring variable of interface types instead of types of the implementing classes is flexibility. You can easily replace the instance implementing the interface without changing your code.

This is a general principle and is not specific to the Collections framework.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • I, for one, sometimes use subtype when I need to emphasize that behavior added by subtype is important. Typical example -- use `HashMap` instead of `Map`, so map will use `hashCode` and not, e.g., `compareTo` for it's operations. – Victor Sorokin Mar 26 '15 at 12:40