THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

supertypes, including interfaces. An object can be used polymorphically with both its superclass and any
superinterfaces, including any of their supertypes.


A class's subtypes are the classes that extend it, including all of their subtypes. An interface's subtypes are the
interfaces that extend it, and the classes that implement it, including all of their subtypes.


Exercise 1.15: Write an interface that extends Lookup to declare add and remove methods. Implement the
extended interface in a new class.


1.13. Generic Types


Classes and interfaces can be declared to be generic types. A generic class or interface represents a family of
related types. For example, in


interface List {
// ... methods of List ...
}


List (read as "list of T") declares a generic list that can be used for any non-primitive type T. You could
use such a declaration to have a list of Point objects (List), a list of String objects
(List), a list of Integer objects (List), and so on. In contrast to a raw List,
which can hold any kind of Object, a List is known to hold only String objects, and this
fact is guaranteed at compile timeif you try to add a plain Object, for example, you'll get a compile-time
error.


Consider the Lookup interface from the previous section, it could be declared in a generic form:


interface Lookup {
T find(String name);
}


Now, rather than returning Object, the find method returns a T, whatever T may be. We could then
declare a class for looking up integers, for example:


class IntegerLookup implements Lookup {
private String[] names;
private Integer[] values;


public Integer find(String name) {
for (int i = 0; i < names.length; i++) {
if (names[i].equals(name))
return values[i];
}
return null; // not found
}


// ...
}

Free download pdf