Given:



public class ComputeSum {

    public int x;
    public int y;
    public int sum;

    public ComputeSum(int nx, int ny) {
        x = nx;
        y = ny;
        updateSum();
    }

    public void setX(int nx) {
        x = nx;
        updateSum();
    }

    public void setY(int ny) {
        x = ny;
        updateSum();
    }

    void updateSum() {
        sum = x + y;
    }
}

This class needs to protect an invariant on the sum field.

Which three members must have the private access modifier to ensure that this invariant is maintained?

A. The x field
B. The y field
C. The sum field
D. The ComputerSum ( ) constructor
E. The setX ( ) method
F. The setY ( ) method

題解

只有在選項C、D、E、F內會更動到sum欄位的值,但是選項D是建構子,在物件實體化的時候才會執行,實體化之就不能再被呼叫了,也就再也沒有機會可以去更動sum欄位的值。

因此去掉選項D之後,答案便是選項C、E、F