File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Principle of Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Principle of "coding to an interface"?" Watch "Principle of "coding to an interface"?" New topic

Principle of "coding to an interface"?

Santiago Bravo
Ranch Hand

Joined: Jul 25, 2008
Posts: 226
K&B SCJP5 book, page 547 says:

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

This kind of declaration follows the object oriented programming principle of "coding to an interface", and it makes use of generics.


Can anyone explain further the principle of "coding to an interface"? Why not just use ArrayList<String> myList = new ArrayList<String>(); instead?

My Path to SCJP Certification My Path to SCWCD Certification
Marco Ehrentreich
best scout

Joined: Mar 07, 2007
Posts: 1294

Hi Santiago,

in your example "List<String>" is the interface and "ArrayList<String>" is a concrete implementation of this interface.

This means that you can call only the methods of the interface on the variable "myList" because List is its declaration type. On the one hand this may seem like a restriction. But on the other hand this approach has the big advantage that your code is not coupled to a specific List implementation but only to the List interface. And this in turn means that you can later substitute the ArrayList with another concrete List implementation like LinkedList for example. This would not be possible if you would not code to the interface and call special ArrayList methods on variable myList!

I hope now it's a bit clearer?!?

Santiago Bravo
Ranch Hand

Joined: Jul 25, 2008
Posts: 226
fantastic, makes sense now Marco.

I agree. Here's the link:
subject: Principle of "coding to an interface"?
It's not a secret anymore!