Cirry's Blog

包装类

2019-09-26
技术
java
最后更新:2024-03-22
2分钟
268字

所有的类的父类就是Object类,但是基本数据类型不是类,所以如果想将基本数据类型以类的方式进行处理,那么就需要对其进行包装。 以int数据为例,进行一个包装处理的定义

1
class Int{
2
private int data; // 包装了一个基本数据类型
3
public Int(int data){
4
this.data = data;
5
}
6
public int intValue(){
7
return this.data;
8
}
9
}
10
public class Bao{
11
public static void main(String args []){
12
Object obj = new Int(10); //装箱: 将基本数据类型保存在包装类中
13
int x= ((Int)obj).intValue(); //拆箱: 从包装对象中获取基本数据类型
14
System.out.println(x*2);
15
}
1 collapsed line
16
}

装箱与拆箱demo

1
public class Bao{
2
public static void main(String args []){
3
Integer obj = new Integer(10); // 装箱 1.9版本之后不建议使用
4
int num = obj.intValue(); // 拆箱
5
System.out.println(num* 2);
6
}
7
}

自动装箱与拆箱——建议使用

1
public class Bao{
2
public static void main(String args []){
3
Integer obj = 10; //自动装箱, 此时不再关心构造方法
4
int num = obj; //自动拆箱
5
obj++; //包装类对象可以直接参与数学运算
6
System.out.println(num);
7
}
8
}
本文标题:包装类
文章作者:Cirry
发布时间:2019-09-26
版权声明:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
感谢大佬送来的咖啡☕
alipayQRCode
wechatQRCode