Information Technology Reference
In-Depth Information
Continuing with the Example
In the stack example just shown, with classes
MyIntStack
and
MyFloatStack
, the bodies of
the declarations of the classes are identical except at the positions dealing with the type of the
value held by the stack.
In
MyIntStack
, these positions are occupied by type
int
.
In
MyFloatStack
, they are occupied by
float
.
You can create a generic class from
MyIntStack
by doing the following:
Take the
MyIntStack
class declaration, and instead of substituting
float
for
int
, substi-
tute the placeholder
T
.
Change the class name to
MyStack
.
Place the string
<T>
after the class name.
The result is the following generic class declaration. The string consisting of the angle
brackets with the
T
means that
T
is a placeholder for a type. (It doesn't have to be the letter
T
—
it could be any identifier.) Everywhere throughout the body of the class declaration where
T
is
located, an actual type will need to be substituted by the compiler.
class MyStack <
T
>
{
int StackPointer = 0;
T
[] StackArray;
public void Push(
T
x ) {...}
public
T
Pop() {...}
...
}