Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
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 The Software Craftsman this week in the Agile 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: 11689

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: 41640
There is a very similar question here. Reading that discussion might help you.
Have you tried LearnNowOnline?
subject: Coding to an interface