Search code examples
javagenericsbounded-types

Bounded Types in generics


Given an example below, why do I need to use doubleValue()(for which it's needed to extend Number class) in reciprocal(), Since there is auto unboxing feature in java which unboxes the numeric object stored in num and can calculate the reciprocal of num and return a double value?

class gen<T extends Number>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num.doubleValue()) ;
     }
 }


public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}

Also, why can't I write the same code as shown below? P.S. : The following code shows error in reciprocal() method:

class gen<T>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num) ;
         // it shows error in the above step. it says "operator / is undefined
     }
 }


public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}

Solution

  • The description for unboxing in Oracle's documentation (https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html) is:

    The Java compiler applies unboxing when an object of a wrapper class is:

    • Passed as a parameter to a method that expects a value of the corresponding primitive type.
    • Assigned to a variable of the corresponding primitive type.

    In your case, you are doing neither of these two.