static 修飾的成員屬於類別本身,而非某個實例。所有實例共享同一份靜態變數,靜態方法無需建立物件即可呼叫。生命週期隨類別載入開始、卸載結束,優於實例存在。
public class Counter {
public static int COUNT = 0; // 共享計數器
public int instanceCount = 0; // 實例變數
}
Counter.COUNT (推薦) 或 obj.COUNT (不推薦,易誤解)。public class MathUtils {
public static int add(int a, int b) { return a + b; } // 工具方法
public static void printStatic() { System.out.println(COUNT); } // 僅能訪問靜態成員
// public void printInstance() { System.out.println(instanceCount); } // 編譯錯誤:無法訪問非靜態
}
this、super 關鍵字不可在靜態上下文使用。public class ConfigLoader {
public static final Map CONFIG = new HashMap<>();
static {
// 類別載入時自動執行,僅一次
try (InputStream is = ConfigLoader.class.getResourceAsStream("/config.properties")) {
Properties p = new Properties(); p.load(is);
p.forEach((k, v) -> CONFIG.put((String)k, (String)v));
} catch (IOException e) { throw new ExceptionInInitializerError(e); }
}
}
public class Outer {
public static class Inner { // 不持有 Outer 實例引用
public void hello() { System.out.println("Static Inner"); }
}
}
// 使用:new Outer.Inner().hello();
Collections.unmodifiableList 或 CopyOnWriteArrayList 保護。