Table of Contents
Introduction
Bounded Type Parameters come into play when you want to restrict what can be passed as parameters in an argument list. As a simple example, if a method strictly deals with numbers, it will want to receive or accept instances of Number and/or its subclasses. Any other type of parameters being passed on to that method will result in data type mismatch. To avoid such circumstances, bounded type parameters can be used.
- When we do not want the whole class to be parameterized, a java generics method can be created. Generic types can be used in constructors as well since constructors are also special types of methods.
- Bounded types are also used when a certain type of objects is required to be restricted. If a method compares two objects, bounded type parameters can make sure that both the objects are Comparables.
- Such bounded type classes will act similar to unbounded classes except that fact that it will throw compile time errors when it encounters a type that does not match its requirements.
Sample Program
The following code determines the largest object and returns it to the system as output. The code makes use of bounded type parameters.
public class DemoMax { //Determines the largest of three comparable objects public static <T extends Comparable<T>> T maximum (T xx, T yy, T zz) { T max = xx;//Assuming xx is the largest if (yy.compareTo(max) > 0) { max = yy; } if (zz.compareTo(max) > 0) { max = zz; } return max } public static void main (String args []) { System.out.println (“Max of”, 31, 41, 51, maximum( 31, 41, 51)); System.out.println (“Max of”, 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7)); } }
OUTPUT
Max of 31, 41, and 51 is 51
Max of 6.6, 8,8 and 7.7 is 8.8
0 Comments