目录
简介
Number类是数字包装类的超类,并且可以看到它实现了Serializable接口,说明它的子类也实现了Serializable。
这个类有6个方法,为xxxValue,xxx为6个原始数字类型,分别代表从这个Number实现类,转换为对应原始类型的值。
/**
* <p>抽象类Number是平台类的超类,代表数字可以转换为原始类型byte,double,float,int,long,short。
*
* <p>从一个特定的Number实现到一个给定的原始类型的转换,这个特殊的语义是有Number的实现定义的。
*
* <p>对于平台类,转换经常类推为转换为变窄或者变宽的原始类型,
* 如在java语言规范中定义的在两个原始类型间转换。
* 因此,转换可能丢失关于数值的总体大小的信息,可能丢失精度,甚至可能返回与输入不同的结果。
*
* <p>可以看Number的实现类的文档,来研究转换的细节。
*
* @author Lee Boynton
* @author Arthur van Hoff
* @jls 5.1.2 Widening Primitive Conversions
* @jls 5.1.3 Narrowing Primitive Conversions
* @since JDK1.0
*/
public abstract class Number implements java.io.Serializable
4个抽象方法
int,long,float,double都是要自己实现的
注意:这些方法的结果对于真正的值,是可能被四舍五入(精度变低,如double到int)或者截断(总体大小变小,如long到int)
因为转换到对应类型,如果从宽到窄,必然有可能损失信息。
/**
* 返回特定数字的int值,该int值可能被四舍五入(精度变低,如double到int)或者截断(总体大小变小,如long到int)
*
* @return the numeric value represented by this object after conversion
* to type {@code int}.
*/
public abstract int intValue();
/**
* Returns the value of the specified number as a {@code long},
* which may involve rounding or truncation.
*
* @return the numeric value represented by this object after conversion
* to type {@code long}.
*/
public abstract long longValue();
/**
* Returns the value of the specified number as a {@code float},
* which may involve rounding.
*
* @return the numeric value represented by this object after conversion
* to type {@code float}.
*/
public abstract float floatValue();
/**
* Returns the value of the specified number as a {@code double},
* which may involve rounding.
*
* @return the numeric value represented by this object after conversion
* to type {@code double}.
*/
public abstract double doubleValue();
2个已经实现的方法
这两个方法都是强转intValue的结果
/**
* Returns the value of the specified number as a {@code byte},
* which may involve rounding or truncation.
*
* <p>这个实现是从intValue方法的结果强制转换到byte类型
*
* @return the numeric value represented by this object after conversion
* to type {@code byte}.
* @since JDK1.1
*/
public byte byteValue() {
return (byte)intValue();
}
/**
* Returns the value of the specified number as a {@code short},
* which may involve rounding or truncation.
*
* <p>这个实现是从intValue方法的结果强制转换到short类型
*
* @return the numeric value represented by this object after conversion
* to type {@code short}.
* @since JDK1.1
*/
public short shortValue() {
return (short)intValue();
}