Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Coding to an interface

 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the benefit of the following statement

List l = new ArrayList();


over the following statement



ArrayList l = new ArrayList();
 
fred rosenberger
lowercase baba
Bartender
Posts: 12122
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
by itself, not much.

However, in the 'real world', you won't always have control like this. Another team may be working on code, and they'll say "we're going to give you a list".

If you find out they are giving you an ArrayList and hard-code it to be such, you are locking in a specific implementation. So you write all your code, relying on it being an ArrayList. The other team then changes their code and returns some other list type. Your code is now broken.

However, if you coded your side to be a List, they can change their code to return ANY list type, and you don't have to change yours at all.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a very similar question here. Reading that discussion might help you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic