Java Reference
In-Depth Information
You can introduce an interface with just the method headers to capture this notion
of the integer list:
1
public interface
IntList {
2
public int
size();
3
public int
get(
int
index);
4
public
String toString();
5
public int
indexOf(
int
value);
6
public void
add(
int
value);
7
public void
add(
int
index,
int
value);
8
public void
remove(
int
index);
9 }
Using the interface, you can write a
processList
method to use in the client
program:
1
public class
ListClient2 {
2
public static void
main(String[] args) {
3 ArrayIntList list1 =
new
ArrayIntList();
4 processList(list1);
5
6 LinkedIntList list2 =
new
LinkedIntList();
7 processList(list2);
8 }
9
10
public static void
processList(IntList list) {
11 list.add(18);
12 list.add(27);
13 list.add(93);
14 System.out.println(list);
15 list.remove(1);
16 System.out.println(list);
17 }
18 }
If this is the only change you make, then your program will include two errors
instead of one. Now both calls on the method cause an error. That seems a bit odd,
because both
ArrayIntList
and
LinkedIntList
have the methods mentioned in the
IntList
interface. But recall that Java requires classes to explicitly state which inter-
faces they implement. So you have to modify the two classes to include this notation:
public class ArrayIntList implements IntList {
...
}
Search WWH ::
Custom Search