aspose file tools*
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
Author

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?


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

Joined: Mar 07, 2007
Posts: 1278

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?!?

Marco
Santiago Bravo
Ranch Hand

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

Cheers!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Principle of "coding to an interface"?
 
Similar Threads
Why create ArrayList of type List?
Collection Query
Collection generics method types
ArrayList Problem
arrays of ArrayList confusion