閱讀994 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Java麵向對象基礎--對象數組

對象數組的聲明


類名 對象數組名稱 【】 = new 類【數組長度】;
class Person{
	private String name ;		// 姓名屬性
	public Person(String name){	// 通過構造方法設置內容
		this.name = name ;		// 為姓名賦值
	}
	public String getName(){
		return this.name ;		// 取得姓名
	}
};
public class ObjectArrayDemo01{
	public static void main(String args[]){
		// 類名稱 數組名稱[] = new 類名稱[長度]
		Person per[] = new Person[3] ;	// 開辟了三個空間大小的數組
		System.out.println("============== 數組聲明 =================") ;
		// 對象數組初始化之前,每一個元素都是默認值
		for(int x=0;x<per.length;x++){	// 循環輸出
			System.out.print(per[x] + "、") ;	// 因為隻是開辟好了空間,所以都是默認值
		}
		// 分別為數組中的每個元素初始化,每一個都是對象,都需要單獨實例化	
		per[0] = new Person("張三") ;	// 實例化第一個元素
		per[1] = new Person("李四") ;	// 實例化第二個元素
		per[2] = new Person("王五") ;	// 實例化第三個元素
		System.out.println("\n============== 對象實例化 =================") ;
		for(int x=0;x<per.length;x++){	// 循環輸出
			System.out.print(per[x].getName() + "、") ;	// 此時,已經實例化完成了,所以會直接打印出姓名
		}
	}
};


class Person{
	private String name ;		// 姓名屬性
	public Person(String name){	// 通過構造方法設置內容
		this.name = name ;		// 為姓名賦值
	}
	public String getName(){
		return this.name ;		// 取得姓名
	}
};
public class ObjectArrayDemo02{
	public static void main(String args[]){
		// 聲明一個對象數組,裏麵有三個對象,使用靜態初始化方式完成
		Person per[] = {new Person("張三"),new Person("李四"),new Person("王五")} ;
		System.out.println("\n============== 數組輸出 =================") ;
		for(int x=0;x<per.length;x++){	// 循環輸出
			System.out.print(per[x].getName() + "、") ;	// 此時,已經實例化完成了,所以會直接打印出姓名
		}
	}
};



最後更新:2017-04-03 15:21:43

  上一篇:go Java麵向對象基礎--this關鍵字的解析
  下一篇:go 設置session過期的各種方式(主要看weblogic的方式)