go to previous page   go to home page   go to next page

Answer:

Yes. main() tries 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 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 it can be altered only through a small number of 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:

(Memory Test: ) In the checking account example, what is the minimum balance for free checking? How much is charged per check below that balance?


go to previous page   go to home page   go to next page