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 并没有实作「Employee(String name, boolean contract, double salary)」这样的构造器。