Given the following class:
public class CheckingAccount {
public int amount;
public CheckingAccount(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
public void changeAmount(int x) {
amount += x;
}
}
And given the following main method, located in another class:
public static void main(String[] args){
CheckingAccount acct = new CheckingAccount((int)(Math.random() * 1000));
//line n1
System.out.println(acct.getAmount());
}
Which three lines, when inserted independently at line n1, cause the program to print a 0 balance?
A.
this.amount = 0;
B.
amount = 0;
C.
acct(0);
D.
acct.amount = 0;
E.
acct.getAmount() = 0;
F.
acct.changeAmount(0);
G.
acct.changeAmount(-acct.amount);
H.
acct.changeAmount(-acct.getAmount());
题解
选项 A,由于 main 方法是在不同的类别,因此使用「this」并不能访问到 acct 对象,会造成编译错误。
选项 B,amount 因为没有声明,所以会造成编译错误。
选项 C,acct 是对象变量,不是方法,无法这样使用。
选项 D,直接访问 acct 变量参考到的对象之字段,是可行的作法。
选项 E,方法不能这样使用,会造成编译错误。
选项 F,因为无法保证 amount 一开始是 0,所以将它加 0 并不一定可以输出 0。
选项 G,amount = amount - amount,所以结果会是 0。
选项 H,理由同选项 G。
