包装类实现原理分析
包装类,因为java的基本数据类型没有对象,如果要让数据类型以类的形式进行处理那就必须要进行包装,所以java给它们都定义对应的包装类。
数据类型对应的包装类:
数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Number的子类:Byte 、Short、Integer、Long、Float 、Double
Object的子类:Character、Boolean
Number里面的方法
拆箱方法 | 说明 |
---|---|
public int intValue() | 从包装类中获取int数据 |
public long longValue() | 从包装类中获取long数据 |
public float floatValue() | 从包装类中获取float数据 |
public double doubleValue() | 从包装类中获取double数据 |
public byte byteValue() | 从包装类中获取byte数据 |
public short shortValue() | 从包装类中获取short数据 |
Object里面的方法
拆箱方法 | 说明 |
---|---|
public char charValue() | 从包装类中获取char数据 |
public boolean booleanValue() | 从包装类中获取boolean数据 |
装箱方法 | 说明 |
---|---|
valueOf | 上面所有包装类都是用这个方法装箱的 |
所有包装类的是被final修饰的不能被子类继承
用int方式来进行拆箱和装箱
class Int {
private int num;
public Int(int num){
this.num = num;
}
public int getInt(){
return this.num;
}
}
class Test {
public static void main(String[] args) {
Object obj = new Int(3); //装箱
int num = ((Int)obj).getInt(); //拆箱
System.out.println(num);
}
}
装箱、拆箱
一般我们是使用包装类来进行装箱和拆箱的,接下来我们用int类型来给大家操作
传统装箱拆箱:
class Test {
public static void main(String[] args) {
Integer in = new Integer(10); //装箱
System.out.println(in.intValue()); //拆箱
}
}
class Test {
public static void main(String[] args) {
Integer in = Integer.valueOf(10); //装箱
System.out.println(in.intValue()); //拆箱
}
}
- valueOf:装箱
- intValue:拆箱
自动装箱拆箱:
class Test {
public static void main(String[] args) {
Integer in = 10;
System.out.println(in); //拆箱
}
}
这样看是不是和基本数据类型赋值一样,这是因为在JDK 1.9之后提供了更加方便的自动装箱和自动拆箱操作,包装类的构造方法虽然没废弃但是不推荐使用了。
数据类型转换
自动转换
自动转换有两个条件
- 转换的类型要兼容
- 要转换的类型必须必转换的范围小
下图是从小到大的范围
class Test {
public static void main(String[] args) {
int i = 10;
//byte b = i; //报错
float f = i;
System.out.println(f); //10
}
}
强制转换
强制转换的条件:
- 格式:(要转换的数据类型)变量名称
class Test {
public static void main(String[] args) {
float f = 10.5f;
System.out.println((int)f); //10
System.out.println(f); //10.5
}
}