所有的类的父类就是Object类,但是基本数据类型不是类,所以如果想将基本数据类型以类的方式进行处理,那么就需要对其进行包装。 以int数据为例,进行一个包装处理的定义
class Int{ private int data; // 包装了一个基本数据类型 public Int(int data){ this.data = data; } public int intValue(){ return this.data; }}public class Bao{ public static void main(String args []){ Object obj = new Int(10); //装箱: 将基本数据类型保存在包装类中 int x= ((Int)obj).intValue(); //拆箱: 从包装对象中获取基本数据类型 System.out.println(x*2); }1 collapsed line
}装箱与拆箱demo
public class Bao{ public static void main(String args []){ Integer obj = new Integer(10); // 装箱 1.9版本之后不建议使用 int num = obj.intValue(); // 拆箱 System.out.println(num* 2); }}自动装箱与拆箱——建议使用
public class Bao{ public static void main(String args []){ Integer obj = 10; //自动装箱, 此时不再关心构造方法 int num = obj; //自动拆箱 obj++; //包装类对象可以直接参与数学运算 System.out.println(num); }}