Reason interfaces are used for list and queue NOT to reduce excessive code.
The main advantage of interfaces is that they allow you to write flexible, loosely coupled code.
(Here's an amazing answer that perfectly describes this concept)
The interface simply defines a list of methods that will be implemented by the class.
This allows us to do a wonderfully powerful thing:
- We can handle all classes that implement the interface in the same way.
This is a HUGE advantage.
Here is a very simple example:
We want to write a debugging method that prints each item in a Collection .
Collection is an interface. It defines a list of operations and does not implement them.
You cannot create an instance of the collection. You can instantiate a class that implements Collection.
There are many classes that implement Collection : ArrayList, Vector, TreeSet, LinkedList, etc. They all have different tricks, but they also have some things in common: since each class implements Collection, they all implement every method found here .
This allows us to do a very powerful thing:
- We can write a method that works with ANY class that implements Collection.
It will look something like this:
public void printCollection(Collection semeCollection) { for (Object o : someCollection) { String s = (o == null) ? "null" : o.toString(); System.out.println(s); } }
Due to the magic of interfaces, we can now do the following:
public void testStuff() { Collection s = new TreeSet(); Collection a = new ArrayList(); Collection v = new Vector(); s.add("I am a set"); a.add("I am an array list"); v.add("I am a vector"); printCollection(s); printCollection(a); printCollection(v); }