In Double object documentation it only have two constructors, one taking a double value and one taking a string value. However, I just found that if we initialize it with other Number type objects it will also work. For example the following code will work:
Integer i = Integer.valueOf(10);
Double d1 = new Double(i);
Long l = Long.valueOf(100);
Double d2 = new Double(l);
So I'm wondering what's behind that? Autoboxing/unboxing would do the conversion between Double/double, Long/long and Integer/int, but I don't see why the constructor of Double will take other data types.
Long l = Long.valueOf(100);
Double d2 = new Double(l);
The above code doesn't make a Double(Long)
call, it makes the available Double(long)
call, with the parameter being unboxed from Long
to long
. This only works because long
is compatible with double
.
So:
However, I just found that if we initialize it with other Number type objects it will also work.
No, you're still calling the same constructor that takes double
as parameter.
As a side note, when you have a Number
object at hand, rather call its doubleValue()
method to get the primitive, instead of creating another object by constructing it using new Double(long)