Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Java Number class implement byteValue() and shortValue()? [duplicate]

Tags:

java

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.

like image 233
Scooter Avatar asked Jul 07 '15 02:07

Scooter


2 Answers

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.

like image 165
paulsm4 Avatar answered Oct 14 '22 20:10

paulsm4


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();
}
like image 39
Makoto Avatar answered Oct 14 '22 20:10

Makoto