核心概念對照
| 維度 | 類變數 (靜態變數) | 實例變數 (非靜態/成員變數) |
| 關鍵字 | static | 無 |
| 別稱 | 靜態成員變數、類屬性 | 對象屬性、非靜態成員 |
| 所屬 | 類別本身 | 具體實例 (對象) |
| 記憶體位置 | 方法區 / Metaspace (JDK 8+) | 堆區 |
| 生命週期 | 類載入時建立,JVM 卸載類時銷毀 | new 實例時建立,GC 回收實例時銷毀 |
| 共享性 | 所有實例共享同一份 | 每個實例擁有獨立副本 |
| 存取方式 | 類別名.變數 (推薦) 或 實例.變數 | 實例.變數 (唯一方式) |
| 初始化時機 | 類載入時靜態初始化區塊/靜態欄位賦值 | 實例化時 (構造器前) |
| 預設值 | 同實例變數 (0, false, null...) | 同左 |
程式碼示範
public class Employee {
// 類變數 (靜態)
static String company = "TechCorp"; // 所有員工共用
static int totalEmployees = 0; // 計數器
static final String COUNTRY = "TW"; // 常數 (慣例全大寫)
// 實例變數
String name; // 姓名
int id; // 工號
double salary; // 薪資
String department; // 部門
// 建構子
public Employee(String name, int id, double salary, String department) {
this.name = name;
this.id = id;
this.salary = salary;
this.department = department;
totalEmployees++; // 修改類變數影響所有實例
}
// 靜態方法只能存取靜態成員
public static void printCompany() {
System.out.println("公司: " + company); // OK
// System.out.println(name); // 編譯錯誤:無法存取非靜態
}
// 實例方法可存取兩者
public void printInfo() {
System.out.printf("%s (ID:%d) - %s - $%.0f [%s]%n", name, id, department, salary, company);
}
}
// 測試
public class Test {
public static void main(String[] args) {
Employee e1 = new Employee("Alice", 1001, 80000, "Engineering");
Employee e2 = new Employee("Bob", 1002, 75000, "Marketing");
e1.printInfo(); // Alice (ID:1001) - Engineering - $80000 [TechCorp]
e2.printInfo(); // Bob (ID:1002) - Marketing - $75000 [TechCorp]
System.out.println("總員工數: " + Employee.totalEmployees); // 2
// 修改類變數
Employee.company = "NewTech";
e1.printInfo(); // Alice ... [NewTech]
e2.printInfo(); // Bob ... [NewTech] ← 兩者同步變化
// 修改實例變數
e1.salary = 85000;
e1.printInfo(); // Alice ... $85000
e2.printInfo(); // Bob ... $75000 ← 不受影響
}
}
記憶體模型圖解
┌─────────────────────────────────────┐
│ Method Area / Metaspace │ ← 類變數 (static)
│ Employee.class │
│ - company = "TechCorp" │
│ - totalEmployees = 2 │
│ - COUNTRY = "TW" │
└─────────────────────────────────────┘
▲
│ 類載入
┌─────────────────────────────────────┐
│ Heap │ ← 實例變數
│ Employee@123 (e1) │
│ - name = "Alice" │
│ - id = 1001 │
│ - salary = 85000 │
│ - department = "Engineering" │
│ │
│ Employee@456 (e2) │
│ - name = "Bob" │
│ - id = 1002 │
│ - salary = 75000 │
│ - department = "Marketing" │
└─────────────────────────────────────┘
常見誤區與最佳實踐
❌ 錯誤:靜態方法中呼叫非靜態成員
public static void bad() {
System.out.println(this.name); // 編譯錯誤:static context 無 this
printInfo(); // 編譯錯誤:無法從靜態上下文呼叫非靜態方法
}
✅ 正確:實例方法存取靜態成員
public void good() {
System.out.println(Employee.company); // 類名.靜態變數 (推薦)
System.out.println(this.company); // 實例.靜態變數 (可行但不推薦,易混淆)
totalEmployees++; // 直接存取靜態變數
}
⚠️ 執行緒安全:類變數非執行緒安全
// 多執行緒環境下 totalEmployees++ 非原子操作
// 解決方案:
static AtomicInteger totalEmployees = new AtomicInteger(0);
// 或
static LongAdder totalEmployees = new LongAdder(); // JDK 8+ 高並發推薦
// 使用
totalEmployees.incrementAndGet(); // 或 totalEmployees.increment()
常數定義規範
// 修飾詞順序:public/private → static → final
public static final int MAX_SIZE = 100;
private static final String DEFAULT_ENCODING = "UTF-8";
// 物件常數:引用不可變,但物件內容可能可變 (需注意)
public static final List EMPTY_LIST = Collections.emptyList(); // 不可變列表
進階:static 區塊與初始化順序
public class InitOrder {
static { System.out.println("1. 父類 static 區塊"); }
static int a = print("2. 父類 static 變數");
{ System.out.println("3. 父類 實例 區塊"); }
int b = print("4. 父類 實例 變數");
public InitOrder() { System.out.println("5. 父類 建構子"); }
static int print(String s) { System.out.println(s); return 0; }
}
class Child extends InitOrder {
static { System.out.println("6. 子類 static 區塊"); }
static int c = print("7. 子類 static 變數");
{ System.out.println("8. 子類 實例 區塊"); }
int d = print("9. 子類 實例 變數");
public Child() { System.out.println("10. 子類 建構子"); }
}
/* 執行 new Child() 輸出順序:
1. 父類 static 區塊
2. 父類 static 變數
6. 子類 static 區塊
7. 子類 static 變數
3. 父類 實例 區塊
4. 父類 實例 變數
5. 父類 建構子
8. 子類 實例 區塊
9. 子類 實例 變數
10. 子類 建構子
*/
總結口訣
- static 隨類走:屬於類、共享、方法區、類名存取
- 非 static 隨對象走:屬於實例、獨立、堆區、實例存取
- 常數加 final:
static final 為編譯期常數,效能最佳
- 多執行緒用原子類:
AtomicInteger、LongAdder 替代 static int 計數器