| 修飾符 | 同類 | 同包 | 子類(異包) | 異包非子類 |
|---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
default (無) | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |
類級別:只能 public 或 default。public 類文件名必須與類名一致,每個文件最多一個 public 類。
ClassName.field(推薦)或 instance.field(不推薦,易誤導)。this 引用。static {
// 類加載時執行,僅一次,常用於靜態字段複雜初始化、註冊驅動
}
class Parent {
static { System.out.println("Parent 靜態塊"); }
{ System.out.println("Parent 實例塊"); }
Parent() { System.out.println("Parent 構造器"); }
}
class Child extends Parent {
static { System.out.println("Child 靜態塊"); }
{ System.out.println("Child 實例塊"); }
Child() { System.out.println("Child 構造器"); }
}
public class Test { public static void main(String[] args) { new Child(); } }
/*
輸出順序:
Parent 靜態塊
Child 靜態塊
Parent 實例塊
Parent 構造器
Child 實例塊
Child 構造器
*/
private、static、final、synchronized、native 共存。abstract。new 實例化,只能被繼承。| 組合 | 合法? | 說明 |
|---|---|---|
| abstract + static | ❌ | 抽象方法無靜態綁定 |
| abstract + final | ❌ | final 禁止繼承/重寫,抽象強制重寫 |
| abstract + private | ❌ | 私有不可繼承 |
| static + final | ✅ | 編譯期常量 static final int MAX = 100; |
| final + 類 | ✅ | 不可被繼承 |
| final + 方法 | ✅ | 不可被重寫 |
| final + 字段 | ✅ | 賦值後不可變(引用不可變,對象內部可變) |
new 實例化final 常量除外,編譯期內聯)Class.forName、ClassLoader.loadClassmain 方法的類)**不會觸發初始化**:聲明引用、訪問父類靜態字段(子類不初始化)、final 常量讀取。
修飾符是 Java 封裝、繼承、多態的語法基石。熟記 **訪問矩陣、static 初始化順序、abstract 契約語義、final 不可變性、組合禁忌**,即可在代碼審查、面試、架構設計中遊刃有餘。