Number n = new Number(5)
is illegal, but Number n = 5
isn't. Why?
Because of autoboxing. 5
is not an object so it is wrapped into an object (Integer
in this case), and Integer
is a Number
.
Number n = 5;
work if Number
is abstract?” See above for how it does. :) –
Maleate Fundamentally, it's because Number
is an abstract class - there is no constructor that corresponds to Number(5)
, and even if there was you still would not be able to instantiate the class directly because it's abstract.
As Bombe explains, in your second case you're really creating an Integer
object* - which, as a subclass of Number
, can be assigned to such a variable. And as it's a concrete class you can instantiate it.
*Although in practice it's actually more equivalent to Integer.valueOf(5)
, which on Sun JREs won't create an additional Integer object but will use a pooled version (like the Flyweight pattern).
It's similar to how the following would work:
List bob = new ArrayList();
List is an interface, so you can't instantiate it directly. However, you can declare a variable of type List and then assign to it a concrete object that implements that interface. Along the same lines, you can declare a variable of type Number and then assign to it any value object that is a concrete instance of that type. What you have done with the functional code is, for all intents and purposes (due to autoboxing):
Number n = new Integer(5);
It shouldn't be. autoboxing is a big mistake.
© 2022 - 2024 — McMap. All rights reserved.