Java麵向對象高級--包裝類
1、包裝類的介紹


這八種包裝類,繼承的父類不全都相同。

數字:


public final class Float
extends Number
implements Comparable<Float>
________________________________________________________________________________________________________________________
2、包裝類的說明



public class WrapperDemo01{
public static void main(String args[]){
int x = 30 ; // 基本數據類型
Integer i = new Integer(x) ; // 裝箱:將基本數據類型變為包裝類
int temp = i.intValue() ; // 拆箱:將一個包裝類變為基本數據類型
}
};
再以小數為例:public class WrapperDemo02{ public static void main(String args[]){ float f = 30.3f ; // 基本數據類型 Float x = new Float(f) ; // 裝箱:將基本數據類型變為包裝類 float y = x.floatValue() ;// 拆箱:將一個包裝類變為基本數據類型 } };

public class WrapperDemo03{ public static void main(String args[]){ Integer i = 30 ; // 自動裝箱成Integer Float f = 30.3f ; // 自動裝箱成Float int x = i ; // 自動拆箱為int float y = f ; // 自動拆箱為float } };
在包裝類中、還有一個最大的特點:就是可以將字符串變為指定的數據類型。
3、包裝類的應用

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)) ; } };
public class WrapperDemo05{ public static void main(String args[]){ int x = Integer.parseInt(args[0]) ; // 將字符串變為int型 float f = Float.parseFloat(args[1]) ; // 將字符串變為float型 System.out.println("整數乘方:" + x + " * " + x + " = " + (x * x)) ; System.out.println("小數乘方:" + f + " * " + f + " = " + (f * f)) ; } };
4、總結

最後更新:2017-04-03 14:53:37