虽然Java语言是典型的面向对象编程语言,但其中的8种基本数据类型并不支持面向对象的编程机制,基本类型的数据不具备“对象”的特性----没有属性、没有方法可调用。沿用他们只是为了迎合程序员根深蒂固的习惯,并能简单、有效地进行常规数据处理。
这种借助于非面向对象技术的做法有时也会带来不便,比如引用类型数据均继承了Object类的特性,要转换为String类型(经常有这种需要)时只要简单调用Object类中定义的toString()即可,而基本数据类型转换为String类型则要麻烦得多。
为解决此类问题,Java语言引入了封装类的概念,在JDK中针对各种基本数据类型分别定义相应的引用类型,并称之为封装类(Wrapper Classes)。
所有的封装类对象都可以向各自的构造器传入一个简单类型数据来构造:
boolean b = true;
Boolean B = new Boolean(b);
byte by = ’42’;
Byte By = new Byte(by);
int i = 123;
Integer I = new Integer(i);
… …
除了Character外,还可以通过向构造器传入一个字符串数据来构造,如果传入的字符串不能用于表示对应的值,除了Boolean类型外,将会抛出一个NumberFormatException异常:
Boolean B = new Boolean("true");
Boolean B1 = new Boolean("a");// 对,不抛出异常
try {
Byte By = new Byte("42");
Short S = new Short("121212");
Integer I = new Integer("123456789");
// … …
} catch (NumberFormatException e) {
e.printStackTrace();
}
封装在封装类中的值,可以通过各自的xxxValue()方法来转换成简单类型:
Boolean----public boolean booleanValue()
Byte----public byte byteValue()
Character----public char charValue()
Double----public double doubleValue()
Float----public float floatValue()
Integer----public int intValue()
Long----public long longValue()
Short----public short shortValue()
下面我们来看一个封装类的例子。
public class WrapperClass {
public static void main(String[] args) {
Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i == j);
}
}
在这个类中,创建了两个int的封装类Integer对象,并且比较它们是否相等。运行这个程序,将在控制台上输出:
false
可以从结果看出,它们并不相等。这是因为,i和j各自指向的对象是不一样的。