public class TestExtend {
class A { ... }
class B extends A { ... }
public static void main(String[] args) {
B b = new B(); // 編譯錯誤:非靜態內部類無法在靜態上下文中引用
}
}
A、B 為非靜態內部類(成員內部類),其實例隱式持有外部類 TestExtend 實例的引用。在 static main 方法中無 this 引用,無法創建內部類實例。
public class TestExtend {
static class A { ... } // 添加 static
static class B extends A { ... } // 添加 static
public static void main(String[] args) {
B b = new B(); // 正常編譯運行
b.f();
}
}
| 類型 | 創建語法 | 訪問外部類實例成員 | 適用場景 |
|---|---|---|---|
| 非靜態內部類 | outer.new Inner() | 可直接訪問(含 private) | 需依賴外部類狀態的輔助類 |
| 靜態內部類 | new Outer.Inner() | 僅能訪問 static 成員 | 獨立工具類、Builder、數據容器 |
static 內部類**,除非確確實實需要訪問外部類實例成員。TestExtend outer = new TestExtend(); B b = outer.new B();