Number class is an abstract class in which you cannot make objects from it using new
operator, but we can use the class as reference Type, I want some explaination for the following code:
public class Test {
public static void main(String[] args) {
Number x = 3;
System.out.println(x.intValue());
System.out.println(x.doubleValue());
}
}
the output is 3 and 3.0
So, in this line Number x = 3;
is there any autoboxing or unboxing(which can't happen it's the superclass) happens? or what?
how the assignment happened here?
The method doubleValue
is abstract
in Number
, but you are storing an Integer
(through auto-boxing) when you do
Number x = 3; // This is Number x = Integer.valueOf(3);
And Integer.doubleValue()
says Returns the value of this Integer as a double after a widening primitive conversion. And it then refers the reader to JLS-5.1.2. Widening Primitive Conversion. Which says, in part, A widening primitive conversion does not lose information about the overall magnitude of a numeric value in the following cases, where the numeric value is preserved exactly: and then lists (specific to this case) from int
to double