The compiler sees that you have tried to access private data from "outside" the object. It 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
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 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.
This is somewhat like putting all the electronics of a TV set
inside of a box,
and allowing the user to change things only by using
the controls on the outside of the box.
TV sets would not last long if users
changed channels by using a screw driver
on the actual
electronics of the set.
(Test of your memory: ) How much money must there be in a checking account before the 15 cents charge per check is dropped?