Tuesday, 11 March 2014

Bounded Type Parameters

Bounded type parameters are the key feature to implement Generic Algorithms.

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number.

Example
<T extends Number> T sum(T var1, T var2)

class Print{
 <T extends Number> void show(T var1, T var2){
  System.out.println(var1 + " is of type " + var1.getClass().getName());
  System.out.println(var2 + " is of type " + var2.getClass().getName());
 }

 public static void main(String args[]){
  Print s1 = new Print();
  s1.show(10,11.12);
 }
}
    
Output
10 is of type java.lang.Integer
11.12 is of type java.lang.Double
    
<T extends Number> void show(T var1, T var2)
As you observe the above statement, 'T' extends the Number class, so T can accept any values, which is of type Number and its sub classes. Since Number is the upper bound for the Type variable 'T'.

Trying to pass values, which is not of type Number causes the compiler error.  

class Print{
 <T extends Number> void show(T var1, T var2){
  System.out.println(var1 + " is of type " + var1.getClass().getName());
  System.out.println(var2 + " is of type " + var2.getClass().getName());
 }

 public static void main(String args[]){
  Print s1 = new Print();
  s1.show("HI", new Object());
 }
}
    
When you tries to compile the above program, compiler throws the below error.









Prevoius                                                 Next                                                 Home

No comments:

Post a Comment