基礎接口:
interface Contents { int value(); }
interface Destination { String readLabel(); }
class Wrapping { Wrapping(int x) {} int value() { return 0; } }
public Destination dest(String s) {
class PDestination implements Destination { ... }
return new PDestination(s);
}
類屬於方法作用域,外部不可見,但返回對象有效。
if (b) {
class TrackingSlip { ... }
TrackingSlip ts = new TrackingSlip("slip");
}
// 此處不可用 TrackingSlip
編譯時仍生成類,但作用域限制使用範圍。
public Contents cont() {
return new Contents() { // 匿名實現 Contents
private int i = 11;
public int value() { return i; }
}; // 分號結束表達式
}
等價於 class MyContents implements Contents ... return new MyContents();。
public Wrapping wrap(int x) {
return new Wrapping(x) { // 調用基類構造器
public int value() { return super.value() * 47; }
};
}
基類構造器參數在 new Wrapping(x) 中傳遞。匿名類無構造器。
public Destination dest(final String dest) {
return new Destination() {
private String label = dest; // 字段初始化
public String readLabel() { return label; }
};
}
使用外部變量必須 final(Java 8+ 隱式 final)。
public Destination dest(final String dest, final float price) {
return new Destination() {
private int cost;
{ // 實例初始化塊 = 匿名類構造器
cost = Math.round(price);
if (cost > 100) println("Over budget!");
}
private String label = dest;
public String readLabel() { return label; }
};
}
初始化塊可執行任意語句(含 if),但不能重載,只能有一個「構造器」。
final(或實際 final)。new SuperType() { ... } 創建衍生類實例並上溯造型。