Answer:
Yes. You have tried to access private data from "outside" the object. The compiler lets you know what it thinks about that:
compiling: CheckingAccountTester.java
CheckingAccountTester.java:46:
Variable balance in class CheckingAccount not accessible from class CheckingAccountTester.
System.out.println( bobsAccount.balance );
^
CheckingAccountTester.java:47:
Variable balance in class CheckingAccount not accessible from class CheckingAccountTester.
bobsAccount.balance = bobsAccount.balance + 200;
^
CheckingAccountTester.java:47:
Variable balance in class CheckingAccount not accessible from class CheckingAccountTester.
bobsAccount.balance = bobsAccount.balance + 200;
^
CheckingAccountTester.java:48:
Variable balance in class CheckingAccount not accessible from class CheckingAccountTester.
System.out.println( bobsAccount.balance );
^
4 errors
Careful Access Control
It may seem a bit silly that the CheckingAccount
class uses private to prevent main()
from seeing its variables,
but then provides methods so that main()
can access them anyway.
The idea of this is that the access methods have control over
each access to the private data.
For example,
a programmer can't increase the balance of a checking account
by writing:
bobsAccount.balance = bobsAccount.balance + 200;
To increase the balance, the processDeposit()
method must be used.
A more elaborate method might check that it was OK to proceed
before adding the deposit to the balance.
It might
check that the account has not been closed,
might ask for a password before it allows access,
and might log every change in a history file.
When data is private
the only changes to it
are made through a small number of access methods.
This helps keep objects consistent and bug-free.
If a bug is detected,
there are only a few places to look for it.
QUESTION 5:
(Test of your memory: ) In the checking account example, what is the minimum balance before the 15 cents charged per check is dropped?