包装类Wrapper(封装类)的使用
包装类(封装类)是针对八种基本数据类型定义相应的引用。
让java中的基本数据类型有了类的特点和功能,就可以调用类中的方法,java才是真正的面向对象。
1、java提供了8种数据类型对应的包装类,使得基本数据类型的变量具有类的特征
基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
doble | Double |
boolean | Boolean |
char | Character |
数值型的(Byte、Short、Integer、Long、Float、Double)的父类是Number
一般源码如下:
public Integer(int value) {
this.value = value;
}
2、基本数据类型、包装类与String类型之间的转换。
1、基本数据类型和包装类的转换
基本数据类型—>包装类
import org.junit.Test;
public class Wrapper_test {
//基本数据类型--->包装类,调用包装类的构造器
@Test//注:不要造个类名为Test
public void test1(){
int num1 = 10;
//System.out.println(num.toString);//基本数据类型无法使用类的方法。
Integer int1 = new Integer(10);//放入变量为int
System.out.println(int1.toString());//10 重写了toString方法。
Integer int2 = new Integer("123");//放入变量为String (String不能包含字符,只能是数字)
System.out.println(int2.toString());//123
//数值类型的与Integer基本相同
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean("true");
Boolean b3 = new Boolean("true123");
System.out.println(b1+"\t"+b2+"\t"+b3);//true true false
Order order = new Order();
System.out.println(order.isMale);
System.out.println(order.isFemale);//null