Java Reference
In-Depth Information
A class can implement Breakable by specifying a data type for T in the implements
statement, as the following Glass class demonstrates:
public class Glass implements Breakable<String> {
public void doBreak(String message) {
System.out.println(“Breaking a Glass: “ + message);
}
}
The Glass declaration denotes String as the data type for T in Breakable , so the
doBreak method must have a String parameter.
The other technique for a class to implement Breakable is to specify another generic as
the data type:
public class Dish<U> implements Breakable<U> {
public void doBreak(U u) {
System.out.println(“Breaking “ + u.toString());
}
}
The data type for the Breakable generic T will be the same as the data type for the
generic U in Dish , which is specifi ed when a Dish is constructed. For example:
Dish<Float> dish = new Dish<Float>();
dish.doBreak(2.7F);
The Dish object uses a Float for its generic, so the parameter for invoking doBreak is a
Float . The output of the previous statement is
Breaking 2.7
As a side note, the U in Dish is arbitrary and in the real world I would probably use a T .
I just wanted to emphasize that the Dish is assigning the generic T in Breakable to another
generic.
Naming Conventions for Generics
You can name your generic types using any valid identifi er. However, the standard
naming convention is to use a single, uppercase letter. Again, use any letter you want,
but in general the following letters are used:
E for an element
K for a map key
Search WWH ::




Custom Search