A Simple Generics Example

Before discussing any more theory, it’s best to look at a simple generics example. The following program defines two classes. The first is the generic class Gen, and the second is GenDemo, which uses Gen.

Image

Image

The output produced by the program is shown here:

Image

Let’s examine this program carefully. First, notice how Gen is declared by the following line:

Here, T is the name of a type parameter. This name is used as a placeholder ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.