Case Study: the Abstract Number Class
Paul Ngugi
Posted on June 17, 2024
Number is an abstract superclass for numeric wrapper classes, BigInteger, and BigDecimal. Numeric wrapper classes, the BigInteger and BigDecimal classes have common methods byteValue(), shortValue(), intValue(), longValue(), floatValue(), and doubleValue() for returning a byte, short, int, long, float, and double value from an object of these classes. These common methods are actually defined in the Number class, which is a superclass for the numeric wrapper classes, BigInteger, and BigDecimal, as shown in below.
Since the intValue(), longValue(), floatValue(), and doubleValue() methods cannot be implemented in the Number class, they are defined as abstract methods in the Number class. The Number class is therefore an abstract class. The byteValue() and shortValue() method are implemented from the intValue() method as follows:
public byte byteValue() {
return (byte)intValue();
}
public short shortValue() {
return (short)intValue();
}
With Number defined as the superclass for the numeric classes, we can define methods to perform common operations for numbers. The program below gives a program that finds the largest number in a list of Number objects.
The program creates an ArrayList of Number objects (line 8). It adds an Integer object, a Double object, a BigInteger object, and a BigDecimal object to the list (lines 9β14). Note that 45 is automatically converted into an Integer object and added to the list in line 9 and that 3445.53 is automatically converted into a Double object and added to the list in line 10 using autoboxing.
Invoking the getLargestNumber method returns the largest number in the list (line 16). The getLargestNumber method returns null if the list is null or the list size is 0 (lines 20β21). To find the largest number in the list, the numbers are compared by invoking their doubleValue() method (line 25). The doubleValue() method is defined in the Number class and implemented in the concrete subclass of Number. If a number is an Integer object, the Integerβs doubleValue() is invoked. If a number is a BigDecimal object, the BigDecimalβs doubleValue() is invoked.
If the doubleValue() method were not defined in the Number class, you will not be able to find the largest number among different types of numbers using the Number class.
Posted on June 17, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.