开发者

If class Number is abstract why I'm I allowed to write Number n = 5?

Number n = new Number(5) is illegal, but Number n = 5 is开发者_Python百科n'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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜