Java Reference
In-Depth Information
Generic Classes
You can introduce generics into your own classes and interfaces. The syntax for
introducing a generic is to declare a formal type parameter in angle brackets, <> . For
example, the following class named Cupboard has a generic type variable declared after the
name of the class:
public class Cupboard<T> {
private T item;
public Cupboard(T item) {
System.out.println(“Cupboard for “ + item.getClass());
this.item = item;
}
public T getItem() {
return item;
}
}
The generic type T is available anywhere within the Cupboard class, and its compile-time
type is determined when a user declares and instantiates a Cupboard object. The following
statements are valid and create three Cupboard objects, each denoting a different data type
for the item fi eld:
4. Cupboard<String> c1 = new Cupboard<String>(“dishes”);
5. Cupboard<Integer> c2 = new Cupboard<Integer>(123);
6. Cupboard<Double> c3 = new Cupboard<Double>(3.14159);
7. String s = c1.getItem();
8. Integer x = c2.getItem();
9. Double d = c3.getItem();
Notice that c1 assigns the generic of Cupboard to be a String type, and then passes in
a String to the constructor. The variable c2 sets its generic type to be Integer and passes
in an Integer (autoboxed) into the constructor. Similarly, c3 uses a Double for its generic.
The constructor of Cupboard prints out the class type of the generic, so the output of the
previous statements is
Cupboard for class java.lang.String
Cupboard for class java.lang.Integer
Cupboard for class java.lang.Double
The calls to getItem on lines 7-9 do not need a cast. The compiler knows the data type
of the return value for each Cupboard instance, a key benefi t to using generics.
Search WWH ::




Custom Search