Card 02/ 08

ExampleDifficulty: Intermediate1 min

A Balance That Only Its Own Methods Can Move

The same account class, and four things a caller might try. Three of them stop at the compiler.

java
Account a = new Account();

a.deposit(5_000);
System.out.println(a.balance());

a.pence = -1;
a.pence -= 10_000;
text
Main.java:6: error: pence has private access in Account
Main.java:7: error: pence has private access in Account

The first two lines work, because the class offered them. The last two do not exist as far as anything outside Account is concerned, so the negative balance that took two days to find can no longer be written at all.

What to notice: balance() returns a long, and a long is a primitive. The caller gets a copy of the number, so there is nothing they can do with it that reaches back into the account.