1

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()) ;
    }

}
Tanjim Ahmed Khan
  • 650
  • 1
  • 9
  • 21
ujzwalp
  • 13
  • 5

2 Answers2

3

Auto-unboxing is not a feature of the Number class, it's a feature of some of its sub-classes (Integer, Double, Float, etc...). There are many sub-classes of Number that don't have this feature (for example, BigInteger, BigDecimal, etc...).

Since the generic type parameter in your first snippet can be of any type that extends Number, it doesn't necessarily have auto-unboxing, so you have to tell the compiler how to convert T to a numeric primitive type that can be an operand of the division operator.

In your second snippet, T has no bound, so it can be anything. The / operator it not defined for any arbitrary type. It is defined for numeric operands. Hence the compiler cannot apply / to 1 and num when num is of some arbitrary reference type.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

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.

Andrei
  • 4,880
  • 23
  • 30