Java Reference
In-Depth Information
In this case, the class (Utility) has no type parameters, but the methods
getMidpoint and getFirst each have a type parameter. Note that the type parameter
in angular brackets, <T> , is placed after all the modifiers—in this case, public
static —and before the returned type.
When you invoke one of these generic methods, preface the method name with the
type to be plugged in, given in angular brackets, as in the following examples:
String midString = Utility.<String>getMidpoint(b);
double firstNumber = Utility.<Double>getFirst(c);
Note that the dot is before the type in angular brackets; the type is part of the method
name, not part of the class name. Also note that the methods getMidpoint and
getFirst use different types plugged in for their type parameter. The type parameter
is local to the method, not to the class. (The argument b is an array with base type
String . The argument c is an array with base type Double .)
You can also define such generic methods inside of generic classes, as in the following
example:
public class Sample<T>
{
private T data;
public Sample(T forData)
{
data = forData;
}
public <ViewerType> void showTo(ViewerType viewer)
{
System.out.println("Hello " + viewer);
System.out.println("Data is " + data);
}
...
}
Note that T and ViewerType are different type parameters. T is a type parameter for
the entire class, but ViewerType is a type parameter only for the method showTo .
What follows is a sample use of these generic methods:
Sample<Integer> object = new Sample<Integer>(42);
object.<String>showTo("Friend");
This produces the output
Hello Friend
Data is 42
 
Search WWH ::




Custom Search