nested class是一種被宣告在class裡面的class,也就是所謂的inner classes,共有四種類型:static member classes、nonstatic member classes、anonymous classes和local classes。
在nested class中,有static
屬性的class,就是static member classes。下面範例,示範了如何撰寫static member class,可以看到Operation
有static
屬性,它的行為就像helper class一樣,不需要被實體化,就可以執行outer class(Calculator)需要它執行的功能。
因為static member classes有static
屬性,所以實作static member class時,不能直接存取和使用enclosing class(outer class)的欄位和方法,就像範例中的Operation
,完全沒有使用Calculator
的欄位和方法,這個特性讓static member classes不只可以成為Nested class,也可以自己獨立出去。
public class Calculator {
// 靜態成員類別
public static class Operation {
public static final Operation PLUS = new Operation("+") {
@Override
public double apply(double x, double y) {
return x + y;
}
};
public static final Operation MINUS = new Operation("-") {
@Override
public double apply(double x, double y) {
return x - y;
}
};
public static final Operation MULTIPLY = new Operation("*") {
@Override
public double apply(double x, double y) {
return x * y;
}
};
public static final Operation DIVIDE = new Operation("/") {
@Override
public double apply(double x, double y) {
if (y == 0) throw new ArithmeticException("Division by zero");
return x / y;
}
};
private final String symbol;
private Operation(String symbol) {
this.symbol = symbol;
}
public String getSymbol() {
return symbol;
}
public double apply(double x, double y) {
throw new UnsupportedOperationException("Operation not implemented");
}
@Override
public String toString() {
return symbol;
}
}
public double calculate(double x, double y, Operation operation) {
return operation.apply(x, y);
}
}
public class ExecuteOperation {
public static void main(String[] args) {
Calculator calculator = new Calculator();
double result1 = calculator.calculate(5, 3, Calculator.Operation.PLUS);
System.out.println("5 + 3 = " + result1);
}
}
nonstatic member class就是沒有static
屬性的Nested class,可以存取所有enclosing class的欄位和方法。跟static member class最大的不同在於:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class CustomCollection<T> {
private T[] items;
private int size;
@SuppressWarnings("unchecked")
public CustomCollection(int capacity) {
items = (T[]) new Object[capacity];
size = 0;
}
public void add(T item) {
if (size < items.length) {
items[size++] = item;
} else {
throw new IllegalStateException("Collection is full");
}
}
public T get(int index) {
if (index >= 0 && index < size) {
return items[index];
} else {
throw new IndexOutOfBoundsException("Index out of bounds");
}
}
public int size() {
return size;
}
public class CustomIterator implements Iterator<T> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < size;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return items[currentIndex++];
}
}
public Iterator<T> iterator() {
return new CustomIterator();
}
}
因為nonstatic member class每次使用都要實體化成物件,比static member class更耗費時間和記憶體,所以設計member class的時候,最好優先設計成static member class,也可以避免memory leak的問題。