Java Reference
In-Depth Information
implementing generic components
using java 5 generics
4.7
We have already seen that Java 5 supports generic classes and that these
classes are easy to use. However, writing generic classes requires a little more
work. In this section, we illustrate the basics of how generic classes and meth-
ods are written. We do not attempt to cover all the constructs of the language,
which are quite complex and sometimes tricky. Instead, we show the syntax
and idioms that are used throughout this topic.
4.7.1 simple generic classes and interfaces
Figure 4.30 shows a generic version of the MemoryCell class previously
depicted in Figure 4.22. Here, we have changed the name to GenericMemoryCell
because neither class is in a package and thus the names cannot be the same.
When a generic class is specified, the class declaration includes one or
more type parameters enclosed in angle brackets <> after the class name. Line 1
shows that the GenericMemoryCell takes one type parameter. In this instance,
there are no explicit restrictions on the type parameter, so the user can create
types such as GenericMemoryCell<String> and GenericMemoryCell<Integer> but
not GenericMemoryCell<int> . Inside the GenericMemoryCell class declaration, we
can declare fields of the generic type and methods that use the generic type as a
parameter or return type.
When a generic
class is specified,
the class declara-
tion includes one or
more type parame-
ters , enclosed in
angle brackets <>
after the class
name.
Interfaces can also be declared as generic. For example, prior to Java 5 the
Comparable interface was not generic, and its compareTo method took an Object
as the parameter. As a result, any reference variable passed to the compareTo
method would compile, even if the variable was not a sensible type, and only
at runtime would the error be reported as a ClassCastException . In Java 5, the
Comparable class is generic, as shown in Figure 4.31. The String class, for
Interfaces can also
be declared as
generic.
figure 4.30
Generic
implementation of the
MemoryCell class
1 public class GenericMemoryCell<AnyType>
2 {
3 public AnyType read( )
4 { return storedValue; }
5 public void write( AnyType x )
6 { storedValue = x; }
7
8 private AnyType storedValue;
9 }
 
 
Search WWH ::




Custom Search