The Java Number class is the base class for the classes that wrap primitive types (Byte, Short, Integer, Long, Float, Double) and also other classes like BigInteger and BigDecimal and has 6 accessor (aka getter) methods:
byte byteValue()
abstract double doubleValue()
abstract float floatValue()
abstract int intValue()
abstract long longValue()
short shortValue()
I don't understand why they didn't make byteValue() and shortValue() also abstract.
Another theory:
Why shortValue() method are concrete but intValue() is abstract into java.lang.Number?
According to the documentation of the Number class, the methods byteValue and shortValue were added first in JDK1.1. This is unlike the other "Value" methods which were already available in the very first JDK release. My assumption is that those two methods were made concrete in order to keep compatibility with existing (also non-standard) subclasses of Number, which would otherwise have been broken by the addition of new abstract methods in the superclass.
Or :
Abstract Methods in Number Class
One look at the source for them says why:
public byte byteValue() { return (byte)intValue(); } public short shortValue() { return (short)intValue(); }
They both rely on the fact that intValue() will be defined, and just use whatever they provide for that. The Number class dates back to Java 1.1... Remember that in Java, longs and ints behave differently, while bytes, shorts are still processed in 32 bit space. Longs -- being 64 bit -- incur additional overhead. So I was guessing that the reason there is no default for intValue() is because they wanted to avoid incurring the possibly unnecessary overhead.
They're not abstract because they're casting the result of intValue()
to their specified type - be that byte
or short
. By that token, these methods are already well-defined; how the intValue
is defined is entirely up to the implementation of the child Number
class.
The documentation at least says that much; here's the source of those two functions to prove it.
public byte byteValue() {
return (byte)intValue();
}
public short shortValue() {
return (short)intValue();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With