Class 是程式的藍圖,就像是一個模子,他會告訴虛擬機器(JVM)如何建置某個型別的物件,根據class建構出的object都會有自己的實體變數,舉例:商店會員資料表而言,每張會員資料卡上都有相同的空白欄位(實體變數),填入新的會員就如同建立一個新的物件,填入資料卡上的資料代表會員的狀態,這張資料卡class上的method就是你會對資料卡做的事,例如:getAddress()、changeTel()、deleteCard()…etc 所以每張資料卡都可以執行相同的動作,但是取出的資料應該是依據每張卡片而各自獨立。
小試身手之小範例:
class Song{
String title;
String singer;
int rating;
void playIt(){
System.out.println("Palying the song");
System.out.println("The song is "+title);
}
}
publicclass SongDrive {
publicstaticvoid main(String[] args){
Song one = new Song();
one.title = "Bad Romance";
one.singer = "Lady gaga";
one.rating = 5;
one.playIt();
Song two = new Song();
two.title = "你不知道的事";
two.singer = "王力宏";
two.rating = 5;
Song three = new Song();
three.title = "憨人";
three.singer = "五月天";
three.rating = 5;
two.playIt();
}
}
輸出畫面
Palying the song
The song is Bad Romance
Palying the song
The song is 你不知道的事