Java Reference
In-Depth Information
Interfaces as specifications
In this chapter, we have introduced interfaces as a means to implement multiple inheritance in
Java. This is one important use of interfaces, but there are others.
The most important characteristic of interfaces is that they completely separate the definition of
the functionality (the class's “interface” in the wider sense of the word) from its implementation.
A good example of how this can be used in practice can be found in the Java collection hierarchy.
The collection hierarchy defines (among other types) the interface List and the classes
ArrayList and LinkedList (Figure 10.5). The List interface specifies the full functionality
of a list, without giving any implementation. The subclasses ( LinkedList and ArrayList )
provide two different implementations of the same interface. This is interesting, because the
two implementations differ greatly in the efficiency of some of their functions. Random access
to elements in the middle of the list, for example, is much faster with the ArrayList . Inserting
or deleting elements, however, can be much faster in the LinkedList .
Figure 10.5
The List interface
and its subclasses
Which implementation is better in any given application can be hard to judge in advance. It
depends a lot on the relative frequency with which certain operations are performed and on
some other factors. In practice, the best way to find out is often to try it out: implement the
application with both alternatives and measure the performance.
The existence of the List interface makes it very easy to do this. If, instead of using
ArrayList or LinkedList as variable and parameter types, we always use List , our appli-
cation will work independently of the specific type of list we are currently using. Only when we
create a new list do we really have to use the name of the specific implementation. We would,
for instance, write
List<Type> myList = new ArrayList<Type>();
Note that the polymorphic variable's type is just List of Type . This way, we can change the
whole application to use a linked list by just changing ArrayList to LinkedList in a single
location when the list is being created.
Exercise 10.57 Which methods do ArrayList and LinkedList have that are not
defined in the List interface? Why do you think that these methods are not included in
List ?
Search WWH ::

Custom Search