Java Reference
In-Depth Information
V for a map value
N for a number
T for a generic data type
Use S , U , V , and so on for multiple types in the same class.
Declaring a generic type at the class level allows the generic to be used anywhere within
the class. You can also declare generics at the method level, which I discuss in the next
section.
Generic Methods
A method or constructor can contain generic type parameters, which makes the method
or constructor generic. You defi ne a generic method by declaring a generic type in angle
brackets before the return value of the method. The scope of the generic type is only within
the method.
To demonstrate, the following Box class contains a generic method named ship. The data
type of the argument is the generic denoted by <T> preceding the method signature, which
means that the parameter's type is not determined until compile time, allowing the ship
method to be invoked with any object type. See if you can determine the result of the Box
program:
1. import java.awt.Frame;
2.
3. public class Box {
4. public static <T> void ship(T item) {
5. System.out.println(“Shipping “ + item.toString());
6. if(item instanceof Frame) {
7. Frame frame = (Frame) item;
8. frame.setSize(200,200);
9. frame.setVisible(true);
10. }
11. }
12.
13. public static void main(String [] args) {
14. Box.ship(“a String object”);
15. Box.ship(args);
16. Box.ship(new Frame());
17. }
18. }
Search WWH ::




Custom Search