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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

any case, a progression requires a way of def<strong>in</strong><strong>in</strong>g its first value <strong>and</strong> it needs a<br />

way of identify<strong>in</strong>g the current value as well.<br />

We beg<strong>in</strong> by def<strong>in</strong><strong>in</strong>g a class, Progression, shown <strong>in</strong> Code Fragment 2.2,<br />

which def<strong>in</strong>es the st<strong>and</strong>ard fields <strong>and</strong> methods of a numeric progression.<br />

Specifically, it def<strong>in</strong>es the follow<strong>in</strong>g two long-<strong>in</strong>teger fields:<br />

• first: first value of the progression;<br />

• cur: current value of the progression;<br />

<strong>and</strong> the follow<strong>in</strong>g three methods:<br />

firstValue(): Reset the progression to the first value, <strong>and</strong> return<br />

that value.<br />

value.<br />

nextValue(): Step the progression to the next value <strong>and</strong> return that<br />

pr<strong>in</strong>tProgression(n): Reset the progression <strong>and</strong> pr<strong>in</strong>t the first n values of<br />

the progression.<br />

We say that the method pr<strong>in</strong>tProgression has no output <strong>in</strong> the sense that it<br />

does not return any value, whereas the methods firstValue <strong>and</strong> nextValue<br />

both return long-<strong>in</strong>teger values. That is, firstValue <strong>and</strong> nextValue are<br />

functions, <strong>and</strong> pr<strong>in</strong>tProgression is a procedure.<br />

The Progression class also <strong>in</strong>cludes a method Progression(), which is a<br />

constructor. Recall that constructors set up all the <strong>in</strong>stance variables at the time<br />

an object of this class is created. The Progression class is meant to be a<br />

general superclass from which specialized classes <strong>in</strong>herit, so this constructor is<br />

code that will be <strong>in</strong>cluded <strong>in</strong> the constructors for each class that extends the<br />

Progression class.<br />

Code Fragment 2.2:<br />

class.<br />

General numeric progression<br />

102

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

Saved successfully!

Ooh no, something went wrong!