You can create a class in Java that defines one or more placeholders for data type. The placeholders are known as generics because the class is not determined until compile time. Generics are notated by angle brackets (< and >). For example, we might wish to create a class that contains a method that accepts an argument of any data type and displays the value of the argument. Because we don't know the data type when we are developing the class, we must use a generic for the method argument data type. To apply basic generics syntax in Java, follow these four steps.
GenericsDisplay. Note the generic parameter
Tafter the class name on line 10. We could use any other letter or a longer name if we wished, but using the one-letter parameter name "T" (as in "Type") is considered best practice, as this letter is used in the Core API. Notice that the data type of the argument in the
displaymethod is T. At compile time, the generic argument type will be replaced with the data type of the parameter that is passed to the method. In the output of this method the value of the argument is displayed along with its data type. In this way, we can verify at run time that the correct data type was communicated to the class using the generic parameter. Two objects are instantiated in the main method, each using a different class name as the value for the generic parameter. Now, all occurrences of T in the
GenericsDisplayclass with be replaced with the class provided when the object is instantiated (e.g.,
String). The main method calls the
displaymethod for each object.