The compiler sees that you have tried to access private data from an "outsider" to 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 used private
to prevent main()
from seeing its variables,
and then provided some methods so that main()
could get at them anyway.
But the idea of this is that the access methods could check
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,
which in a more elaborate program might
check that the account is not frozen,
might insist on a password before it changes anything,
and might write a log file of every change.
By declaring data to be private
and by
forcing the use of access methods,
it is easier to keep objects consistent and bug-free.
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 customarily
changed channels by using a screw driver on the actual
electronics of the set.