Java Reference
In-Depth Information
Generic Basics
Classes and methods can have a type parameter. The type parameter may then have any
reference type, and hence any class type, plugged in for the type parameter. This plugging
in produces a specific class type or method. For example, Display 14.4 shows a very simple
class definition with a type parameter T . You may use any nonkeyword identifier for the
type parameter; you need not use T . However, by convention, type parameters start with
an uppercase letter, and there is some tradition of using a single letter for a type parameter.
Starting with an uppercase letter makes sense because typically a class type is plugged in for
the type parameter. The tradition of using a single letter is not so compelling.
A class definition with a type parameter is stored in a file and compiled just like
any other class. For example, the parameterized class shown in Display 14.4 would be
stored in a file named Sample.java . Once the parameterized class is compiled, it can
be used like any other class, except that when used in your code, you must specify a
class type to be plugged in for the type parameter. For example, the class Sample from
Display 14.4 could be used as follows:
type
parameter
Sample<String> object1 = new Sample<String>();
object1.setData("Hello");
System.out.println(object1.getData());
Sample<Pet> object2 = new Sample<Pet>();
Pet p = new Pet();
<Some code to set the data for the object p>
object2.setData(p);
The class Pet can be as defined in Chapter 4, but the details do not matter; it could be
any class.
A class, such as Sample<String> , that you obtain from a generic class by plugging
in a type for the type parameter is said to instantiate the generic class. So, we would
say “ Sample<String> instantiates the generic class Sample . ”
Notice the angular bracket notation for the type parameter and also for the class
type that is plugged in for the type parameter.
instantiate
Display 14.4
A Class Dei nition with a Type Parameter
1 public class Sample<T>
2 {
3 private T data;
4 public void setData(T newData)
5 {
6 data = newData;
7 }
T is a parameter for a type.
8 public T getData()
9 {
10 return data;
11 }
12 }
 
 
Search WWH ::




Custom Search