iT邦幫忙

2024 iThome 鐵人賽

DAY 25
0

nested class是一種被宣告在class裡面的class,也就是所謂的inner classes,共有四種類型:static member classesnonstatic member classesanonymous classeslocal classes

什麼是static member class?

在nested class中,有static屬性的class,就是static member classes。下面範例,示範了如何撰寫static member class,可以看到Operationstatic屬性,它的行為就像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?

nonstatic member class就是沒有static屬性的Nested class,可以存取所有enclosing class的欄位和方法。跟static member class最大的不同在於:

  • 因為可以存取enclosing class的欄位和方法,所以無法自己獨立出去。
  • 每次使用都要實體化成物件。
    nonstatic member class常用於Adapter的實作。Adapter的設計方式,可以用於class之間的轉換,以達成資料結構的轉換,像下面的範例,把Collection轉換成Iterator,nonstatic member class可以當作Adapter,協助Collection轉換成像Stack這種資料結構的Iterator。
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的問題。


上一篇
Day 24: 偏好使用interfaces而不是抽象類別(abstract class)(下)
下一篇
Day 26: Nested class的四種類型(下)
系列文
深入淺出Java 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言