Java Reference
In-Depth Information
implementing generic
components using inheritance
4.6
Recall that an important goal of object-oriented programming is the support
of code reuse. An important mechanism that supports this goal is the
generic
mechanism: If the implementation is identical except for the basic
type of the object, a
generic implementation
can be used to describe the
basic functionality. For instance, a method can be written to sort an array of
items; the
logic
is independent of the types of objects being sorted, so a
generic method could be used.
Generic
program-
ming allows us to
implement type-
independent logic.
Unlike many of the newer languages (such as C++, which uses templates
to implement generic programming), before version 1.5 Java did not support
generic implementations directly. Instead, generic programming was imple-
mented using the basic concepts of inheritance. This section describes how
generic methods and classes can be implemented in Java using the basic prin-
ciples of inheritance.
Direct support for generic methods and classes was announced by Sun in
June 2001 as a future language addition. Finally, in late 2004, Java 5 was
released and provided support for generic methods and classes. However,
using generic classes requires an understanding of the pre-Java 5 idioms for
generic programming. As a result, an understanding of how inheritance is
used to implement generic programs is essential, even in Java 5.
In Java, genericity
is obtained by using
inheritance.
4.6.1
using
Object
for genericity
The basic idea in Java is that we can implement a generic class by using an
appropriate superclass, such as
Object
.
Consider the
IntCell
class shown in Figure 3.2. Recall that the
IntCell
supports the
read
and
write
methods. We can, in principle, make this a generic
MemoryCell
class that stores any type of
Object
by replacing instances of
int
with
Object
. The resulting
MemoryCell
class is shown in Figure 4.22.
There are two details that must be considered when we use this strat-
egy. The first is illustrated in Figure 4.23, which depicts a
main
that writes a
"37"
to a
MemoryCell
object and then reads from the
MemoryCell
object. To
access a specific method of the object we must downcast to the correct
type. (Of course in this example, we do not need the downcast, since we are
simply invoking the
toString
method at line 9, and this can be done for any
object.)
A second important detail is that primitive types cannot be used. Only
reference types are compatible with
Object
. A standard workaround to this
problem is discussed momentarily.
Search WWH ::
Custom Search