ABSTRACT

The previous chapter built an interface and two implementations for an integer stack. Suppose now that we need a stack to hold strings. (We are about to need one, in fact, in Section 4.4.) With copy-paste and some careful editing, we could create a StringStack interface and two corresponding string implementations. But then what if we need a stack to hold some other type? You can see the problem: continuing to write new classes and interfaces for every element type creates a lot of code that is essentially the same. What we need is a type variable, so that each time we make a new stack, we can specify the type that will be stored in it. This is known as generic programming.

A generic type (interface or class) is defined by including one or more type parameters in angle brackets at the end of the name of the interface or class:

or