Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Principle of "coding to an interface"?

 
Santiago Bravo
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fantastic, makes sense now Marco.

Cheers!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic