Bounded Generics in Java

Other Java Topics

This is a continuation of our tutorials on Java Generics.

As you know, Generics in Java allows for data types to be defined as a generic type in design time and the actual datatype is determined at run time.

In case of bounded generic type, we  would wan to restrict the data types tat can be used in the type parameter <T> certain data types. For instance, we may want to restrict the type to Number-related data types i.e classes derived from Number class.  How do we do that?

One way to achieved this is by specifying the class name along with the generic parameter declarations. In this case, then the generic type is restricted to only the class specified and the classes derived from it.

The syntax for this is:

 public static <T extends Comparable<T>> T GetMax(T x, T y, T z)
 {
	//Body of the method
 }

Listing 1.0: Bounded generic type declaration

How it Works

  • The first T, specifies the generic type.
  • Comparable refers to the class such that the generic type is restricted to object of this type and classed derived from it.
  • The second T is the return type
  • GetMax is the name of the method
  • T x, T y and T z specifies the types for the argument to the function

We now present the complete program below.

/*
 * Program to demonstrated bounded generics
 * by: Kindson The Genius
 */
public class GenericTut {

	public static void main(String[] args) {
		System.out.printf("Max is for integers: %d \n", GetMax(6,3,9) );
		
		System.out.printf("Max is strings is %s \n" , GetMax("Elephant","Cat", "Monkey"));
		
		System.out.printf("Max for char is %c \n", GetMax('c','r','y'));
	}

	public static <T extends Comparable<T>> T GetMax(T x, T y, T z)
	{
		T max = x;
		if(y.compareTo(max)> 0)
		{
			max = y;
		}
		if(z.compareTo(max)>0)
		{
			max = z;
		}
		return max;
	}
}

Listing 1.1: Complete Program on Bounded Generics

Copy this program into your compiler (you can use Netbeans or Eclipse) and make sure you understand how it works.

If you run it correctly, then your output would be like shown in Figure .10

Figure 1.0: Program Output for Bounded Generics
User Avatar

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

Leave a Reply

Your email address will not be published. Required fields are marked *