Given the code fragment:



public class Employee {

    String name;
    boolean contract;
    double salary;

    Employee() {
        // line n1
    }

    public String toString() {
        return name + ":" + contract + ":" + salary;
    }

    public static void main(String[] args) {
        Employee e = new Employee();
        // line n2
        System.out.print(e);
    }
}

Which two modifications, when made independently, enable the code to print joe:true:100.0?

A.
Replace line n2 with:

e.name = "Joe";
e.contract = true;
e.salary = 100;
B.
Replace line n2 with:
this.name = "Joe";
this.contract = true;
this.salary = 100;
C.
Replace line n1 with:
this.name = new String("Joe");
this.contract = new Boolean(true);
this.salary = new Double(100);
D.
Replace line n1 with:
name = "Joe";
contract = TRUE;
salary = 100.0f;
E.
Replace line n1 with:
this("Joe", true, 100);

題解

由於name、contract和salary都是Employee物件的物件變數,需要先實體化之後透過物件參考才可以存取,因此選項A是可以的。

選項B由於main方法是屬於類別(靜態)方法,並沒有實體,無法使用this關鍵字。

選項C是在Employee物件的建構子內直接修改其物件變數的值,因此是正確的。

選項D並沒有「TRUE」這個boolean值。

選項E並沒有實作「this(String name, boolean contract, double 100)」這樣的建構子。