在 Java 中,若在外部類的靜態方法(如 main)中直接實例化非靜態內部類,編譯器會報錯:
No enclosing instance of type Outer is accessible.
Must qualify the allocation with an enclosing instance of type Outer
(e.g. x.new A() where x is an instance of Outer).
public class Paixu {
public static void main(String[] args) {
// 錯誤:嘗試在 static 方法中 new 非靜態內部類
MaoPaoSort mp = new MaoPaoSort();
}
class MaoPaoSort { // 非靜態內部類
public void test1() { /* ... */ }
}
}
非靜態內部類實例隱含持有外部類實例的引用,因此必須先有外部類實例,才能建立內部類實例。在 static 方法中沒有 this 參考,故無法直接 new。
static class MaoPaoSort { ... }
Paixu outer = new Paixu();
MaoPaoSort mp = outer.new MaoPaoSort();
若內部類不需存取外部類的非靜態欄位/方法,務必加上 static 修飾詞,使其成為巢狀靜態類,避免不必要的外部實例綁定,並提升記憶體效率。