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.

Sometimes, <strong>in</strong> a <strong>Java</strong> class, it is convenient to reference the current <strong>in</strong>stance of<br />

that class. <strong>Java</strong> provides a keyword, called this, for such a reference. Reference<br />

this is useful, for example, if we would like to pass the current object as a<br />

parameter to some method. Another application of this is to reference a field<br />

<strong>in</strong>side the current object that has a name clash with a variable def<strong>in</strong>ed <strong>in</strong> the<br />

current block, as shown <strong>in</strong> the program given <strong>in</strong> Code Fragment 2.1.<br />

Code Fragment 2.1: Sample program illustrat<strong>in</strong>g<br />

the use of reference this to disambiguate between a<br />

field of the current object <strong>and</strong> a local variable with the<br />

same name.<br />

When this program is executed, it pr<strong>in</strong>ts the follow<strong>in</strong>g:<br />

The dog local variable =5.0<br />

The dog field = 2<br />

An Illustration of Inheritance <strong>in</strong> <strong>Java</strong><br />

To make some of the notions above about <strong>in</strong>heritance <strong>and</strong> polymorphism more<br />

concrete, let us consider some simple examples <strong>in</strong> <strong>Java</strong>.<br />

In particular, we consider a series of several classes for stepp<strong>in</strong>g through <strong>and</strong><br />

pr<strong>in</strong>t<strong>in</strong>g out numeric progressions. A numeric progression is a sequence of<br />

numbers, where each number depends on one or more of the previous numbers.<br />

For example, an arithmetic progression determ<strong>in</strong>es the next number by addition<br />

<strong>and</strong> a geometric progression determ<strong>in</strong>es the next number by multiplication. In<br />

101

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

Saved successfully!

Ooh no, something went wrong!