靜態變數
了解利用static關鍵字修飾變數時的程式意義,以及相關使用方式。
在前一篇我們知道用static修飾的成員,在程式載入時會一起載入記憶體,但在Java的程式裡面又代表什麼意義呢?
從物件導向的觀點去看物件的資料欄位:
class Human{
Sring name;
int age;
int height;
Human(String str){
name=str;
}// end of constructor(String)
}// end of class Human
這個類別叫Human裡面有3個欄位,分別紀錄該物件的姓名、年齡及身高。
創造物件:
Human tina = new Human("小婷");
Human yubin = new Human("小木");
記憶體配置:
此時各個物件擁有的資料欄位彼此獨立,佔用不同記憶體空間,互不干涉。
我們知道在Human裡面定義的資料欄位(name, age, height)是屬於『物件』的。創造物件後,每個物件都有自己的資料欄位。
但如果我希望有一個欄位可以『全部物件共同擁有』呢?
例如:希望能有一個變數,紀錄總共的人數。
那很明顯,這個變數不應該屬於『某個物件』,而是屬於『類別』。
class Human{
static int total = 0; // 紀錄總人數
Sring name;
int age;
int height;
Human(String str){
name=str;
total++; // 每建立一個Human物件,即對總人數+1
}// end of constructor(String)
}// end of class Human
創造物件:
class Test{
public static void main(String[] args){
Human tina = new Human("小婷");
System.out.println("目前人數:"+Human.total);
Human yubin = new Human("小木");
System.out.println("目前人數:"+Human.total);
}// end of main(String[])
}// end of class Test
執行結果:
目前人數:1
目前人數:2
記憶體配置:

與一般物件成員不同,static成員是屬於類別,也就是所謂『類別成員』。
存取方式:
類別名稱 . 靜態成員 ;
就像我們存取一般物件的變數一樣,透過點運算子,但因為靜態成員是屬於類別所以要用類別名稱去存取。
題外話
存取靜態成員的方式其實更加自由,以上述寫的Human類別為例:
class Test{
public static void main(String[] args){
Human tina = new Human("小婷");
Human yubin = new Human("小木");
System.out.println(Human.total);
System.out.println(tina.total);
System.out.println(yubin.total);
}// end of main(String[])
}// end of class Test
輸出結果:
2
2
2
從程式中看到,物件tina跟物件yubin,都可以透過點運算子對total這個類別成員進行存取。這是沒問題的,因為tina、yubin都是Human類別,相當於透過Human去存取。
但是『非常不建議』這種寫法,寫程式要考慮到程式的可讀性,類別成員就用類別名稱去存取,物件成員就用物件名稱去存取,讀程式的人才不會造成混淆。
甚至有些人以為類別成員一定要用類別名稱存取(害我被扣分還要去跟老師要分數),因此考慮到對Java不熟的人可能會看你的程式,還是照著建議的方式撰寫(Java建議寫法)。
以上述例子來看,要存取 total,就應該用類別名稱去存取:
System.out.println(Human.total);
Last updated
Was this helpful?