, meaning T can only be replaced by Number or its subclasses. The document then provides two examples of bounded type parameters, one displaying values and one finding the maximum of three Comparable objects. It also describes restrictions on generic types, such as not being able to instantiate type parameters or create arrays of generic references.">, meaning T can only be replaced by Number or its subclasses. The document then provides two examples of bounded type parameters, one displaying values and one finding the maximum of three Comparable objects. It also describes restrictions on generic types, such as not being able to instantiate type parameters or create arrays of generic references.">
Bounded Type Parameters
Bounded Type Parameters
There may be times when you want to restrict the types that can be used as type arguments in a
parameterized type. For example, a method that operates on numbers might only want to accept
instances of Number or its subclasses. This is what bounded type parameters are for.
For example, If you want a generic class that works only with numbers (like int, double, float,
long …..) then declare type parameter of that class as a bounded type to java.lang.Number class.
Then while creating objects to that class you have to pass only Number types or it’s subclass
types as type parameters.
class Gen
{
static < S , T extends Number> void display(S t, T v)
{
System.out.println(v.getClass().getName()+" = " +v);
System.out.println(t.getClass().getName()+" = " +t);
}
public static void main(String[] args)
{
display("88",6); // CASE 1: S can be any data but T both should be a Number ( < S , T extends Number>)
//display(1,2); //S T both should be a Number ( < S extends Number, T extends Number>)
//display("100","C"); // S T both should not be a Number ( < S , T>)
}
}
Output:
java.lang.Integer = 6
java.lang.String = 88
Output 2:
Compile Errors :
prog.java:12: error: method display in class Gen cannot be applied to given types;
display("100","C"); // S T both should not be a Number ( < S , T>)
^
required: S,T
Example 2:
if(y.compareTo(max) > 0)
{
max = y; // y is the largest so far
}
if(z.compareTo(max) > 0)
{
max = z; // z is the largest now
}
return max; // returns the largest object
}
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6,
8.8, 7.7 ));
OUTPUT:
Max of 3, 4 and 5 is 5
Max of A, B and C is C
Gen() {
ob = new T(); // Illegal!!!
}
}
No static member can use a type parameter declared by the enclosing class.
For example, all of the static members of this class are illegal:
class Wrong<T> {
// Wrong, no static variables of type T.
static T ob;
// ja v a2 s . c o m
// Wrong, no static method can use T.
static T getob() {
return ob;
}
You can declare static generic methods with their own type parameters.
Generic Array Restrictions
You cannot instantiate an array whose base type is a type parameter. You
cannot create an array of type specific generic references.