Yes. The idea of encapsulation is to hide the details of an object from other sections of the software. Some of the details might be methods.
class CheckingAccount { // data-declarations private String accountNumber; private String accountHolder; private int balance; private int useCount = 0; private void incrementUse() { ___________________ } void processDeposit( int amount ) { incrementUse(); balance = balance + amount ; } void processCheck( int amount ) { int charge; incrementUse(); if ( balance < 100000 ) charge = 15; else charge = 0; balance = balance - amount - charge ; } }
A private method is one that can be used only by the other methods of an object. Parts of a program outside of the object cannot directly invoke (use) a private method of the object.
Say that the bank wants to keep track of how many
times each checking account is used.
(This might be done as a security measure.)
A "use" of the checking account is processing a deposit
or a check.
To do this, a "use count" is added to the data of the
CheckingAccount
class (some parts of the class have been temporarily left out).
The processDeposit()
and processCheck()
methods
call incrementUse()
to increase the use count each time they are used.
We want the use count to change for these two reasons only,
so the incrementUse()
method is made private
(and the variable useCount
is also made private.)