How to Use Basic Generics Syntax in Java

  • google plus

In Brief...

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.

Instructions

  1. Open your text editor and type in the following Java statements:
    Java Source for Basic Generics
    The class that contains the generic syntax is named GenericsDisplay. Note the generic parameter T after 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 display method 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 GenericsDisplay class with be replaced with the class provided when the object is instantiated (e.g., String). The main method calls the display method for each object.
  2. Save your file as BasicGenericsSyntax.java.
  3. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
    Compile Source for Basic Generics
  4. Type in the command to run your program and hit Enter. Notice in the output that a String variable and a Date variable were each successfully passed to the generic class method.
    Run for Basic Generics

Related Video

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss