When should I use an interface in java? [closed]

A good place to look at would be the collections framework.

java.util.List //interface

java.util.ArrayList //Concrete class
java.util.LinkedList //Concrete class

So you can write code like this:

List l = new ArrayList();

l.add(..)
//do something else.

If in future you want to change the implementation with say LinkedList or you own AwesomeList which implements List interface, all you have to do is change the very first line to:

List l = new MyAwesomeList();
or
List l = new LinkedList();

The rest of the code would follow through.

Leave a Comment