23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

We show the CreditCard class <strong>in</strong> Code Fragment 1.5. Note that the<br />

CreditCard class def<strong>in</strong>es five <strong>in</strong>stance variables, all of which are private to the<br />

class, <strong>and</strong> it provides a simple constructor that <strong>in</strong>itializes these <strong>in</strong>stance variables.<br />

It also def<strong>in</strong>es five accessor methods that provide access to the current values of<br />

these <strong>in</strong>stance variables. Of course, we could have alternatively def<strong>in</strong>ed the <strong>in</strong>stance<br />

variables as be<strong>in</strong>g public, which would have made the accessor methods moot. The<br />

disadvantage with this direct approach, however, is that it allows users to modify an<br />

object's <strong>in</strong>stance variables directly, whereas <strong>in</strong> many cases such as this, we prefer to<br />

restrict the modification of <strong>in</strong>stance variables to special update methods. We<br />

<strong>in</strong>clude two such update methods, chargeIt <strong>and</strong> makePayment <strong>in</strong> Code<br />

Fragment 1.5.<br />

In addition, it is often convenient to <strong>in</strong>clude action methods, which def<strong>in</strong>e specific<br />

actions for that object's behavior. To demonstrate, we have def<strong>in</strong>ed such an action<br />

method, the pr<strong>in</strong>tCard method, as a static method, which is also <strong>in</strong>cluded <strong>in</strong><br />

Code Fragment 1.5.<br />

The Test Class<br />

We test the CreditCard class <strong>in</strong> a Test class. Note the use of an array,<br />

wallet, of CreditCard objects here, <strong>and</strong> how we are us<strong>in</strong>g iteration to<br />

make charges <strong>and</strong> payments. We show the complete code for the Test class <strong>in</strong><br />

Code Fragment 1.6. For simplicity's sake, the Test class does not do any fancy<br />

graphical output, but simply sends its output to the <strong>Java</strong> console. We show this<br />

output <strong>in</strong> Code Fragment 1.7. Note the difference between the way we utilize the<br />

nonstatic chargeIt <strong>and</strong> make-Payment methods <strong>and</strong> the static pr<strong>in</strong>tCard<br />

method.<br />

Code Fragment 1.5: The CreditCard class.<br />

69

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!