一 、包裝類(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
}
}
(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()方法
}
}