Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
A funny BankAccount


The following output appears when I run the program:

Peter's account holds 1000 kroner
Balance = 2000
Peter's account holds 1000 kroner
Peter's account holds 2050 kroner

The expression ba.Balance returns twice the actual balance of the account: 2000.

The assignment

   ba.Balance += 100;

is equivalent to

   ba.Balance = Ba.Balance + 100;

The value of the expression

   Ba.Balance + 100

is 2100. When the setter of Balance is applied, 2100 - 50 = 2050 is assigned to the instance variable balance.