QuestionQ226

Working with Methods and Encapsulation

Given these two classes:

Question Image

Any electricity amount used by a customer, represented by an instance of the Customer class, must contribute to that customer's bill, represented by the member variable bill, through the useElectricity method.

An instance of the Customer class must never be able to alter or reduce the value of the member variable bill.

How should the methods in the ElectricAccount class be written at line n1 so that bill always equals the value of kWh multiplied by the value of rate?

  • A
  • B
  • C
  • D
Explanation

addKWh must be public so Customer.useElectricity can call it, and it must accept only positive usage so a caller cannot reduce accumulated kWh or bill. Recomputing bill as kWh * rate after increasing kWh maintains the required invariant without exposing a public method that can set bill arbitrarily.

Community Discussion

No comments yet. Be the first to start the discussion!