简体   繁体   中英

Why don't Java wrapper classes have no-arg constructors?

What is the rationale of not providing no-arg constructors in Wrapper Classes? I know that they were inherently built for Wrapping primitive types, so the right way is to provide a primitive type for constructors.

However, considering primitive types have no-arg constructor, why don't they have one?

Besides, if they had no-arg constructors, they could be instantiated as T.class.newInstance() . However, since newInstance() requires no-arg constructor, this won't work with Wrapper Classes.

Wrapper objects are immutable. This means that once a wrapper object has a value assigned to it, that value cannot be changed. It doesn't make much sense to have a default value for an object whose value can't be changed. You wouldn't want to get a newInstance() of a wrapper class, because then you'd be stuck with the default value.

I think it's because the values wrapped by these classes are meant to be final immutable ( that was the word I was looking for, thanks Bill:)). If there was a default constructor, it would be quite useless, as you couldn't change the the primitive wrapped by the class later on.

There's no use in providing the primitive type in a constructor. The type of the wrapper class indicates the primitive type. Since an instantiated wrapper object cannot change (immutable), there is only one chance of giving it a value: during its construction. If wrapper class objects were not immutable, strange things could happen. If you would have a default wrapper class constructor, what would its value be?

A better question would be why do they have constructors at all. We should be just interested in the value. The object identity is irrelevant to the meaning of the types.

Most (but not all) uses of reflection are pointless. Construction of an immutable value like this would have very little value. Class.newInstance is particularly evil due to its exception behaviour. T.class where T is a generic parameter will not compile due to erasure.

Only objects have constructors, primitives don't have constructors so they don't have a default constructor. Primitives get their default value by virtue of objects/values being initialised to all 0 bytes. (Which is false in boolean, 0.0f in float, 0.0 in double and null as a reference)

You appears to want to create an object with newInstance() however the only uninitialised value is null.

很可能是因为虽然基元具有默认值(0、0.0f、0.0、0L、false 等),但包装器通常将这些默认值表示为 null。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM