0

I encountered with a strange issue. I don't understand why this code doesn't work:

public static <Type1 extends  Integer, Type2 extends Double > 
               Object addition(Type1 first, Type2 second)
     {
         return second * first;
     }

The compiler claims Operator * cannot be applied to Type2,Type1. But that types extends Integer and Double which has + operator defined for them. So i really don't understand this

4

2 回答 2

9

You are wrong. Neither Integer nor Double or any other objects extending Number class have "+" or any other operator definied. The only reason why you are able to perform something like (Integer + Double) is autoboxing. And autoboxing is a kind of "hardcoded" feature which applies to a very small predefined set of classes, such as Integer, Double, etc.

Furthermore, Integer and all other Number subclasses are declared "final", therefore "Type extends Integer" has no meaning, since you cannot extend anything from Integer.

于 2013-07-21T14:43:17.747 回答
0

The simplest solution is to use double which can store every possible int values.

public static double addition(double first, double second)
 {
     return second + first;
 }

I assume you wanted + for addition, not * for multiplication

you can run

 double d1 = addition(1, 5.5);
 double d2 = addition(10.1, 5);
 double d3 = addition(1, 2);
 double d4 = addition(10.1, 12.3455);

There is no point extending a final class. Your types are basically the types you gave.

于 2013-07-21T17:13:47.160 回答