img
What Are Generics?
At its core, the term generics means parameterized types. Parameterized types are important
because they enable you to create classes, interfaces, and methods in which the type of data
upon which they operate is specified as a parameter. Using generics, it is possible to create
a single class, for example, that automatically works with different types of data. A class,
interface, or method that operates on a parameterized type is called generic, as in generic class
or generic method.
It is important to understand that Java has always given you the ability to create generalized
classes, interfaces, and methods by operating through references of type Object. Because Object
is the superclass of all other classes, an Object reference can refer to any type object. Thus, in
pre-generics code, generalized classes, interfaces, and methods used Object references to
operate on various types of objects. The problem was that they could not do so with type safety.
Generics add the type safety that was lacking. They also streamline the process, because
it is no longer necessary to explicitly employ casts to translate between Object and the type
of data that is actually being operated upon. With generics, all casts are automatic and implicit.
Thus, generics expand your ability to reuse code and let you do so safely and easily.
NOTE  A Warning to C++ Programmers: Although generics are similar to templates in C++, they
OTE
are not the same. There are some fundamental differences between the two approaches to generic
types. If you have a background in C++, it is important not to jump to conclusions about how
generics work in Java.
A Simple Generics Example
Let's begin with a simple example of a generic class. The following program defines two
classes. The first is the generic class Gen, and the second is GenDemo, which uses Gen.
// A simple generic class.
// Here, T is a type parameter that
// will be replaced by a real type
// when an object of type Gen is created.
class Gen<T> {
T ob; // declare an object of type T
// Pass the constructor a reference to
// an object of type T.
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
return ob;
}
// Show type of T.
void showType() {
System.out.println("Type of T is " +
ob.getClass().getName());
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home