Given the following two classes:

public class Customer {

    ElectricAccount acct = new ElectricAccount();

    public void useElectricity(double kWh) {
        acct.addKWh(kWh);
    }
}
public class ElectricAccount {

    private double kWh;
    private double rate = 0.07;
    private double bill;

    // line n1
}

How should you write methods in the ElectricAccount class at line n1 so that the member variable bill is always equal to the value of the member variable kwh multiplied by the member variable rate?

Any amount of electricity used by a customer (represented by an instance of the customer class) must contribute to the customer's bill (represented by the member variable bill) through the method useElectricity method. An instance of the customer class should never be able to tamper with or decrease the value of the member variable bill.

A.

public void addKWh(double kWh){
    this.kWh += kWh;
    this.bill = this.kWh * this.rate;
}
B.
public void addKWh(double kWh){
    if(kWh > 0){
        this.kWh += kWh;
        this.bill = this.kWh * this.rate;
    }
}
C.
private void addKWh(double kWh){
    if(kWh > 0){
        this.kWh += kWh;
        this.bill = this.kWh * this.rate;
    }
}
D.
public void addKWh(double kWh){
    if(kWh > 0){
        this.kWh += kWh;
        setBill(this.kWh);
    }
}

public void setBill(double kWh){
    bill = kWh * rate;
}

题解

选项 A,没有判断传入的 kWh 参数的值是否大于 0,因此可能会有传入负数的情形。

选项 B,正确答案。

选项 C,使用 private 来修饰 addKWh 方法,会导致 ElectricAccount 之外的其他类别无法访问。

选项 D,setBill 方法应该要改成 private 来修饰,避免帐单被窜改。