What is the purpose of the Number class?

I have often come across questions such as Java Generics and adding numbers together , and the answer usually comes down to the fact that you cannot do anything with help Numberon its own.

The source code shows that Numberit is basically an empty shell, unlike the Object example.

At this moment, I cannot imagine a situation where using Numberinstead of a specific subtype has significant (if any) advantages. I usually start with Number, but run into problems later, actually use it and change it to a subtype anyway. But this can only be my limited experience.

So, I wonder, what is the purpose of this class, which then is the common ancestor of other number types without real functionality?

+2
source share
5 answers

As you can see in Javadocs, this is an abstract class. By definition, then its sole purpose is to serve as a base class for other number types. There is a set of methods (for example intValue()) that each subclass will have Number, and you can imagine something like

if (object instanceof Number)
    result = ((Number) object).intValue();
else if (object instanceof String)
    result = Integer.parseInt(object.toString());

I think about this. What else do you expect?

+3
source

It allows the following:

  • Performing (possibly loss) conversion from one type to another.
  • Allows you to write client code to use a more accurate form ( longor double) while maintaining lower values.
  • , (long) (Object).
  • (Integer) (BigInteger)... .
  • , (long vs. AtomicLong), .
  • , , Fraction, double.
  • API- , IntegerCursor. , , .
+1

Java Number, Number , Java- , . .

0

, , , Byte, Short, , , Float Double. , . . .

public abstract class java.lang.Number extends java.lang.Object implements java.io.Serializable
{
     //......
}

, Number

0

Well, I wanted him to at least implement Comparable, but I see how Integer.compareTo (SomeNumberType) might not match SomeNumberType.compareTo (Integer); and why only subclasses implement Comparable.

0
source

All Articles