File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Coding to an interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Coding to an interface" Watch "Coding to an interface" New topic

Coding to an interface

Rajiv Rai
Ranch Hand

Joined: Jun 14, 2010
Posts: 57
What is the benefit of the following statement

List l = new ArrayList();

over the following statement

ArrayList l = new ArrayList();
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11957

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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46437
There is a very similar question here. Reading that discussion might help you.
I agree. Here's the link:
subject: Coding to an interface
It's not a secret anymore!