Reputation: 8247
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.
Upvotes: 2
Views: 3989
Reputation: 533580
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.
Upvotes: 1
Reputation: 147164
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.
Upvotes: 1
Reputation: 3596
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?
Upvotes: 2
Reputation: 405815
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.
Upvotes: 11
Reputation: 20782
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.
Upvotes: 2
Reputation: 5491
Most likely because while primitives have a default value ( 0, 0.0f, 0.0, 0L, false etc), the Wrappers usually express these default values as null.
Upvotes: 0