anonymous class就像anonymous這個字,"匿名"描述的一樣,簡單的說就是沒有名字的類別。這個特殊的類別有幾個特性:
static,也不能宣告有static屬性的欄位。總而言之,anonymous class就像一個過客,急急忙忙出現,任務結束後又默默的消失,所以常被用來當function object,舉例來說,collection要做sorting的時候,需要Comparator作為比大小的條件,就可以直接使用anonymous class實作Comparator並實體化物件。
List<Integer> studentIds = new ArrayList<Integer>();
Collections.sort(studentIds, new Comparator<Integer>() {
    public int compare(Integer s1, Integer s2) {
        return s1.compareTo(s2); // 使用 compareTo 方法進行比較
    }
});
也可以用來實作collection架構中的AbstractInterface,像是Day 24: 偏好使用interfaces而不是抽象類別(abstract class)(下)的範例一樣,作為兩個資料結構轉換的Adapter。
import java.util.AbstractList;
import java.util.List;
public class ConvertType {
    static List<Integer> intArrayAsList(final int[] a) {
        if (a == null) {
            throw new NullPointerException();
        }
        return new AbstractList<Integer>() {
            @Override
            public Integer get(int index) {
                return a[index];
            }
            @Override
            public int size() {
                return a.length;
            }
        };
    }
    public static void main(String[] args) {
        int[] myArray = {1, 2, 3};
        List<Integer> myList = intArrayAsList(myArray);
        System.out.println(myList);
    }
}
local class是所有nested class中使用頻率最低的。它跟member class一樣都有名字,跟anonymous class一樣都不能宣告有static屬性的欄位,可以在程式裡面,被匡住的地方宣告和使用,像是方法、if和foor迴圈匡住的地方,就跟下面範例一樣,被宣告在sum()這個範圍的Summation就是local class。
public class Calculator {
    public int sum(int[] numbers) {
        class Summation {
            public int calculateSum() {
                int total = 0;
                for (int number : numbers) {
                    total += number;
                }
                return total;
            }
        }
        Summation summation = new Summation();
        return summation.calculateSum();
    }
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        int[] numbers = {1, 2, 3, 4, 5};
        int result = calculator.sum(numbers);
        System.out.println("Sum: " + result);  // 輸出結果:Sum: 15
    }
}
參考文件: