I looked for a duplicate of this but don't see a replica similar enough to satisfy.
You can't instantiate abstract classes in Java, and Number is abstract, so why does this line compile:
Number num = 3;
If it was Integer num, it would get autoboxed, but does autoboxing somehow work for Number too, even though it's abstract? Or is something else happening?
It’s not that auto-boxing works for Number
. You are fully correct, the Number
class is abstract and cannot be instantiated. Also no general mechanism for auto-boxing a primitive number into a Number
object exists in Java.
It’s that auto-boxing works from int
to Integer
. The literal 3
is an int
(with no exception). And Integer
is a concrete subclass of Number
, so putting a reference to an Integer
into a variable declared as Number
is trouble-free.
It may be a bit surprising that it works, I agree with you. The basic rule of auto-boxing is you can put an int
where an Integer
is expected, a double
where a Double
is expected, and so forth. We can hardly say that an Integer
was necessarily expected on the right-hand side of your initialization. It seems they have extended the rule to be applicable here anyway. And it’s no doubt in the JLS somewhere (JLS: Java Language Specification).
Just for checking we may do:
Number num = 3;
System.out.println(num.getClass());
Output:
class java.lang.Integer
You may extend the rule one step further:
Object obj = 3;
It still gives you an Integer
(not just an Object
even though Object
is a concrete class).
Link: Similar question: Does Java autobox when assigning an int to an Object? (you will also find the references to JLS there)