天天看点

Number 类源码解读定义属性方法方法测试

定义

Number 类定义如下:

package java.lang;
public abstract class Number implements java.io.Serializable
           

从这里我们可以了解到以下几点:

  1. 该类是 java.lang 包下的一个抽象类。
  2. 继承了 io 的 Serializable 接口,因此该类可以进行序列化操作。

作为抽象类,它是 BigDecimal、BigInteger、Byte、Double、Float、Integer、Long 和 Short 类的父类。因此所有继承 Number 类的子类都需要提供该抽象类中定义的方法。

属性

该属性值是为了序列化定义的,具体序列化的内容会在以后详细说明。

方法

它提供了以下方法:

public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() {
    return (byte)intValue();
}
public short shortValue() {
    return (short)intValue();
}
           

我们可以看到这些方法都是 xxxValue,其作用就是将数据值转换为相对应的类型。

方法声明 作用 返回值类型
intValue 获取数值类对应的int数值 返回int
longValue 获取数值类对应的long数值 返回long
floatValue 获取数值类对应的float数值 返回float
doubleValue 获取数值类对应的double数值 返回double
byteValue 获取数值类对应的byte数值 返回byte
shortValue 获取数值类对应的short数值 返回short

方法测试

测试代码:

public class Test {
    public void testInteger() {
        Integer num = new Integer(10);
        System.out.println("intValue(): " + num.intValue());
        System.out.println("longValue(): " + num.longValue());
        System.out.println("floatValue(): " + num.floatValue());
        System.out.println("doubleValue(): " + num.doubleValue());
        System.out.println("byteValue(): " + num.byteValue());
        System.out.println("shortValue(): " + num.shortValue());
    }
}
           

测试结果:

intValue(): 10
longValue(): 10
floatValue(): 10.0
doubleValue(): 10.0
byteValue(): 10
shortValue(): 10