I would like the method to accept ints, and doubles. Can the Number class be used as an argument, so that all numbers can be accepted as parameters. (I suspect that it could apply, but only to Integers, rather than ints.)
Yes, autoboxing works to convert int
to Number
just as well as from int
to Integer
:
public class Test {
public static void main(String[] args) throws Exception {
foo(10);
foo(10.5);
foo(10.5f);
foo(java.math.BigInteger.ONE);
}
static void foo(Number number) {
System.out.println(number + " " + number.getClass());
}
}
Or rather, boxing itself only converts from int
to Integer
, but then a widening reference conversion converts from Integer
to Number
. From JLS 5.3:
Invocation contexts allow an argument value in a method or constructor invocation (§8.8.7.1, §15.9, §15.12) to be assigned to a corresponding formal parameter.
Strict invocation contexts allow the use of one of the following:
- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
Loose invocation contexts allow a more permissive set of conversions, because they are only used for a particular invocation if no applicable declaration can be found using strict invocation contexts. Loose invocation contexts allow the use of one of the following:
- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
- a boxing conversion (§5.1.7) optionally followed by widening reference conversion
- an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion
In this case the loose invocation context is used (for the first three invocations of foo
) as no method declaration can be found using strict invocation contexts.
See more on this question at Stackoverflow