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.

Figure 2.5 : Inheritance diagram for class<br />

Progression <strong>and</strong> its subclasses.<br />

To complete our example, we def<strong>in</strong>e a class TestProgression, shown <strong>in</strong><br />

Code Fragment 2.6, which performs a simple test of each of the three classes. In<br />

this class, variable prog is polymorphic dur<strong>in</strong>g the execution of the ma<strong>in</strong><br />

method, s<strong>in</strong>ce it references objects of class ArithProgression,<br />

GeomProgression, <strong>and</strong> FibonacciProgression <strong>in</strong> turn. When the ma<strong>in</strong><br />

method of the TestProgression class is <strong>in</strong>voked by the <strong>Java</strong> run-time<br />

system, the output shown <strong>in</strong> Code Fragment 2.7 is produced.<br />

The example presented <strong>in</strong> this section is admittedly small, but it provides a simple<br />

illustration of <strong>in</strong>heritance <strong>in</strong> <strong>Java</strong>. The Progression class, its subclasses, <strong>and</strong><br />

the tester program have a number of shortcom<strong>in</strong>gs, however, which might not be<br />

immediately apparent. One problem is that the geometric <strong>and</strong> Fibonacci<br />

progressions grow quickly, <strong>and</strong> there is no provision for h<strong>and</strong>l<strong>in</strong>g the <strong>in</strong>evitable<br />

overflow of the long <strong>in</strong>tegers <strong>in</strong>volved. For example, s<strong>in</strong>ce 3 40 > 2 63 , a geometric<br />

progression with base b = 3 will overflow a long <strong>in</strong>teger after 40 iterations.<br />

Likewise, the 94th Fibonacci number is greater than 2 63 ; hence, the Fibonacci<br />

progression will overflow a long <strong>in</strong>teger after 94 iterations. Another problem is<br />

that we may not allow arbitrary start<strong>in</strong>g values for a Fibonacci progression. For<br />

example, do we allow a Fibonacci progression start<strong>in</strong>g with 0 <strong>and</strong> −1 ? Deal<strong>in</strong>g<br />

with <strong>in</strong>put errors or error conditions that occur dur<strong>in</strong>g the runn<strong>in</strong>g of a <strong>Java</strong><br />

program requires that we have some mechanism for h<strong>and</strong>l<strong>in</strong>g them. We discuss<br />

this topic next.<br />

109

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

Saved successfully!

Ooh no, something went wrong!