Card 02/ 08

ExampleDifficulty: Intermediate1 min

Encapsulation Example: A Balance Only Its Own Methods Can Change

Four things a caller might try, and two of them stop at the compiler.

Code outside a class can use its public methods and cannot name its private fields. An Account class holds its balance in private long pence and offers deposit and balance() methods. Four lines a caller might write:

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
    a.pence = -1;
     ^
Main.java:7: error: pence has private access in Account
    a.pence -= 10_000;
     ^
2 errors

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 no code outside the class can set a negative balance at all.

Notice that 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.