Given:



class Cake {

    int model;
    String flavor;

    Cake() {
        model = 0;
        flavor = "Unknown";
    }
}

public class Test {

    public static void main(String[] args) {
        Cake c = new Cake();
        bake1(c);
        System.out.println(c.model + " " + c.flavor);
        bake2(c);
        System.out.println(c.model + " " + c.flavor);
    }

    public static Cake bake1(Cake c) {
        c.flavor = "Strawberry";
        c.model = 1200;
        return c;
    }

    public static void bake2(Cake c) {
        c.flavor = "Chocolate";
        c.model = 1230;
        return;
    }
}

What is the result?

A.

0 unknown
0 unknown

B.

1200 Strawberry
1200 Strawberry

C.

1200 Strawberry
1230 Chocolate

D. Compilation fails

題解

Cake類別和其物件欄位都沒有加上修飾字,因此預設的存取範圍在同一個套件之下,當然也包括第12行的Test類別。

程式第22行的bake1方法,將物件欄位設定為c.flavor = "Strawberry", c.model = 1200。

程式第28行的bake2方法,將物件欄位設定為c.flavor = "Chocolate", c.model = 1230。