原文標題「外部類」實指 內部類。Java 中定義在另一個類內部的類稱為內部類,分四類:
public class Cow {
private double weight;
private class CowLeg { // private 修飾,外部不可見
private double length;
private String color;
public void info() {
System.out.println("牛腿顏色:" + color + ",長度:" + length);
System.out.println("所屬奶牛重量:" + weight); // 直接訪問外部類 private 欄位
}
}
public void test() {
CowLeg leg = new CowLeg();
leg.info();
}
}
特性:
private/protected/public/default 修飾new CowLeg()Outer$Inner.classpublic class Outer {
private int instanceVar = 5;
private static int staticVar = 9;
static class StaticNested {
public void access() {
// System.out.println(instanceVar); // 編譯錯誤:靜態類不可訪問實例成員
System.out.println(staticVar); // 僅可訪問外部類 static 成員
}
}
}
特性:
new Outer.StaticNested()interface Product {
double getPrice();
String getName();
}
public class Demo {
public void test(Product p) {
System.out.println("購買:" + p.getName() + ",價格:" + p.getPrice());
}
public static void main(String[] args) {
new Demo().test(new Product() { // 現場實作介面
public double getPrice() { return 567.8; }
public String getName() { return "RTX 4090"; }
});
}
}
規則:
| 特性 | 成員內部類 | 靜態巢狀類 | 匿名內部類 |
|---|---|---|---|
| 訪問外部實例成員 | ✓ 直接訪問 | ✗ 僅 static | ✓ (若在實例方法中) |
| 可定義 static 成員 | ✗ | ✓ | ✗ |
| 需外部實例建立 | ✓ | ✗ | 視上下文 |
| 修飾符支援 | 全部 | static + 存取修飾符 | 無 |
| 編譯產出 | Outer$Inner.class | Outer$Nested.class | Outer$1.class, Outer$2.class... |