How to Write Type Parameters with Multiple Bounds in Java

  • google plus

In Brief...

A generic type can be bounded with multiple class data types. The class types that qualify are subclasses of a specified data type or implementations of an interface. For example, we might wish to create a vector or array list and call a method in a generic class to process the data. Both the ArrayList and Vector classes are implementations of the List interface. Therefore the bounds of the generic parameter are the implementations of List. To learn how to write type parameters with multiple bounds in Java, follow these four steps.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. Open your text editor and type in the following Java statements:
    Java Source for Multiple Bounds
    The class GenericsMultipleBounds (line 15) is defined with the clause <T extends List> which means the generic type is bounded by implementations of the List interface. ArrayList and Vector are common examples of List implementations and are referred to as collections. The main method instantiates two GenericMultipleBounds objects. An array list is passed to the first object's display method. A vector is passed to the second object's display method. The display method will print the first item of the collection that was passed.
  2. Save your file as WriteTypeParametersWithMultipleBounds.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 Multiple Bounds
  4. Type in the command to run your program and hit Enter. Notice in the output that the first item of the array list was displayed followed by the first item stored in the vector.
    Run Multiple Bounds

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