Java Reference
In-Depth Information
public class LinkedIntList implements IntList {
...
}
After you make this change, the code compiles and executes properly.
It is important to keep in mind that you can't create instances of the interface type.
The following line of code is an error:
IntList list = new IntList(); // error-can't instantiate the interface
Interfaces cannot be instantiated because they are incomplete. They specify behav-
iors, but they don't say how those behaviors are implemented. So when you create an
instance, you have to pick one of the actual implementations.
Even though you can't create an instance of an interface, it is a good idea to use
interfaces when you define the types of variables. Therefore, method main in the
client code should be rewritten as follows:
public static void main(String[] args) {
IntList list1 = new ArrayIntList();
processList(list1);
IntList list2 = new LinkedIntList();
processList(list2);
}
These variables are more flexible than the old variables. The variable list1 , for
example, can now refer to any IntList object, not just one of type ArrayIntList .
16.5 LinkedList<E>
In this section we will use the LinkedIntList that we have developed to produce a
class that is similar to Java's LinkedList<E> class. In the collections framework, there
is a close relationship between the LinkedList<E> class and the ArrayList<E> class.
We'll mirror that relationship in the version that we create. The task will require mak-
ing a few changes to the ArrayList<E> that we developed at the end of the previous
chapter.
In particular, we'll introduce an interface List<E> that both classes will imple-
ment. We can include all of the methods that we implemented for the ArrayList<E> .
We can also introduce a slight improvement. Various structures can use the for-
each loop that was introduced in Chapter 7. If you want to be able to use a for-each
loop for your own class, you have to implement a special interface known as
Iterable<E> . It has one and only one method:
public interface Iterable<E> {
public Iterator<E> iterator();
}
 
Search WWH ::




Custom Search