[2014-3-21]JAVA笔记_包装类(Wrapper Class)、匿名内部类

一 、包装类(Wrapper Class)。针对于原生数据类型的包装。所有的包装类(8个)都位于java.lang 包下。

1. 包装类的作用:将基本数据类型包装成类的形式。


包装类中的继承关系:(1) Integer、Byte、Float、Double、Short、Long 都属于 Number 类的子类, Number类本身提供了一系类的返回以上6中基本数据类型的操作。

(2) Character  属于 Object 的直接子类。

(3) Boolean 属于 Object 的直接子类。

Number 类是一个抽象类,主要是将数字包装类中的内容变为基本数据类型。


2. 包装类的 装箱 与 拆箱 概念:

            装箱: 将一个基本数据类型变为包装类。

            拆箱: 将一个包装类变为基本数据类型。

//包装类
public class IntegerTest{
	public static void main(String[] args){
		int a = 10;
		Integer integer = new Integer(a);

		int b = integer.intValue();

		System.out.println(a == b);

	}
}

//浮点数装箱及拆箱
public class WrapperDemo02{
	public static void main(String args[]){
		float f = 30.0f;				//声明一个基本数据类型
		Float x = new Float(f);			//装箱:将基本数据类型变为包装类
		float y = x.floatValue();		//拆箱:将一个包装类变为基本数据类型
	}
}
以上都属于手工装箱及拆箱操作,在JDK1.5之后提供了自动装箱及拆箱操作。

//自动装箱及拆箱操作
public class WrapperDemo03{
	public static void main(String args[]){
		Integer i = 30;			//自动装箱成Integer
		Float f = 30.f;			//自动装箱成Float
		int x = i;				//自动拆箱为int
		float y = f;			//自动拆箱为Float
	}
}


3. 包装类的应用: 将字符串变为基本数据类型。

(1) Integer 类(字符串转 int 型)
public static int parseInt(String s) throws NumberFormatException

(2) Float 类(字符串转 Float 型)

public static float parseFloat(String s) throws NumberFormatException
但是在使用以上两种操作时,一定要注意字符串必须由数字组成。

//字符串转变为基本数据类型
public class WrapperDemo04{
	public static void main(String args[]){
		String str1 = "30";			//由数字组成的字符串
		String str2 = "30.3";		//由数字组成的字符串
		int x = Integer.parseInt(str1);			//将字符串变为int型
		float f = Float.parseFloat(str2);		//将字符串变为Float型
		System.out.println("整数乘方:" + x + " * " + x + " = " + (x * x));
		System.out.println("小数乘方:" + f + " * " + f + " = " + (f * f));
	}
}

二、匿名内部类

匿名内部类就是指没有一个具体名称的类。在接口和抽象类应用上比较多。

//匿名内部类
interface A{
	public void printInfo();			//定义抽象方法
} 
class X{
	public void fun1(){			//定义fun1()方法
		this.fun2(new A(){				//匿名内部类
			public void printInfo(){			//实现接口中的抽象方法
				System.out.println("Hello World!!!");
			}
		});			//new A(){} 直接实例化接口对象
	}
	public void fun2(A a){			//接收接口实例
		a.printInfo();			//调用接口方法
	}
}
public class NoInnerClassDemo02{
	public static void main(String args[]){
		new X().fun1();			//实例化X类对象并调用fun1()方法
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章