Given:



class Alpha {

    int ns;
    static int s;

    Alpha(int ns) {
        if (s < ns) {
            s = ns;
            this.ns = ns;
        }
    }

    void doPrint() {
        System.out.println("ns = " + ns + " s = " + s);
    }
}

public class TestA {

    public static void main(String[] args) {
        Alpha ref1 = new Alpha(50);
        Alpha ref2 = new Alpha(125);
        Alpha ref3 = new Alpha(100);
        ref1.doPrint();
        ref2.doPrint();
        ref3.doPrint();
    }
}

What is the result?

A.

ns = 50 s = 125
ns = 125 s = 125
ns = 100 s = 125

B.

ns = 50 s = 125
ns = 125 s = 125
ns = 0 s = 125

C.

ns = 50 s = 50
ns = 125 s = 125
ns = 100 s = 100

D.

ns = 50 s = 50
ns = 125 s = 125
ns = 0 s = 125

題解

ns是物件變數,s是類別變數,s在物件的變化會影響到其他的物件。在第6行的Alpha建構子中,會使用比原先的s更大的值來初始化ns和s。main方法並非從小到大將數值傳給Alpha的建構子並實體化出不同的物件,第22行傳入的125是最大值,之後第23行傳入建構子的100將會使得第7行的if條件式不成立,而沒有在建構子中被初始化的ns變數數值預設是0。

因此答案是選項B。