Java Reference
In-Depth Information
Class Definition with a Type Parameter
You can define classes with a parameter for a type. Such a class is called a generic class or a
parameterized class . The type parameter is included in angular brackets after the class
name in the class definition heading. You may use any nonkeyword identifier for the type
parameter, but by convention, the type parameter starts with an uppercase letter. The type
parameter may be used like any other type in the definition of the class. (There are some
restrictions on where the type parameter can be used. These are discussed in the Pitfall sec-
tion entitled “Type Parameters Cannot Be Used Everywhere a Type Name Can Be Used.”) For
an example, see Display 14.4.
A generic class is used like any other class, except that you specify a reference type, typi-
cally a class type, to be plugged in for the type parameter. This class type (or other reference
type) is given in angular brackets after the name of the generic class, as shown in the follow-
ing example:
EXAMPLE
Sample<String> object1 = new Sample<String>();
object1.setData("Hello");
Sample<String> is said to instantiate the generic class Sample .
TIP: Compile with the -Xlint Option
There are many pitfalls that you can encounter when using type parameters. If you
compile with the -Xlint option, you will receive more informative diagnostics of any
problems or potential problems in your code. For example, the class Sample in Display
14.4 should be compiled as follows:
javac -Xlint Sample.java
If you are using an IDE to compile your programs, check your documentation to see
how to set compiler options. (For the TextPad environment, you can set compiler
options in the Preferences box under the Configure menu.)
When compiling with the -Xlint option, you will get more warnings than you
would otherwise get. A warning is not an error, and if the compiler gives only warn-
ings and no error message, then the class has compiled and can be used. However, in
most cases, be sure you understand the warning and feel confident that it does not
indicate a problem, or else change your code to eliminate the warning. One warning
that you may get on some programs in this text is “no definition of serialVersion-
UID .” Discussion of this warning is beyond the scope of this topic, but you can safely
ignore the warning.
Search WWH ::




Custom Search