Josh:
First, my book has in-depth coverage of generics. In fact, the generics chapter is nearly 50 pages long. There is a lot to generics, far more than one or two examples can show.
That said, here is a
very simple example that shows how to create a generic class and create an object of that class. Pay close attention to the new syntax elements.
The output produced is shown here.
value: 88
value: Generics
Test The key point is that the
Gen class is generic. Its type parameter is
T, which is a placeholder for the real type that will be known when an object of type
Gen is instantiated. Thus,
Gen<Integer> creates an
Gen reference in which
Integer is substituted for
T.
Gen<String> creates a reference in which
String is substituted for
T. (Actually, the process used by the
Java generics system is
type erasure, not substitution, but conceptually that is how it appears to the programmer.) Most importantly, these types are
enforced by the compiler.
For example, assuming the preceding program, this line will not compile because of a type mismatch error.
In the program,
iOb is of type
Gen<Integer>. Because of this, it can't be assigned a reference to a
Double object. This is a key feature of generics: type safety.
Josh, frankly, there is a whole lot more to generics than this simple example shows, but it gives you a look at the basic syntax.
Here are other important features of generics: bound types, wildcards, raw types, erasure, bridge methods, and potential ambiguity.