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.

The ma<strong>in</strong> "actors" <strong>in</strong> a <strong>Java</strong> program are objects. Objects store data <strong>and</strong> provide<br />

methods for access<strong>in</strong>g <strong>and</strong> modify<strong>in</strong>g this data. Every object is an <strong>in</strong>stance of a class,<br />

which def<strong>in</strong>es the type of the object, as well as the k<strong>in</strong>ds of operations that it<br />

performs. The critical members of a class <strong>in</strong> <strong>Java</strong> are the follow<strong>in</strong>g (classes can also<br />

conta<strong>in</strong> <strong>in</strong>ner class def<strong>in</strong>itions, but let us defer discuss<strong>in</strong>g this concept for now):<br />

• <strong>Data</strong> of <strong>Java</strong> objects are stored <strong>in</strong> <strong>in</strong>stance variables (also called fields).<br />

Therefore, if an object from some class is to store data, its class must specify the<br />

<strong>in</strong>stance variables for such objects. Instance variables can either come from base<br />

types (such as <strong>in</strong>tegers, float<strong>in</strong>g-po<strong>in</strong>t numbers, or Booleans) or they can refer to<br />

objects of other classes.<br />

• The operations that can act on data, express<strong>in</strong>g the "messages" objects respond to,<br />

are called methods, <strong>and</strong> these consist of constructors, procedures, <strong>and</strong> functions.<br />

They def<strong>in</strong>e the behavior of objects from that class.<br />

How Classes Are Declared<br />

In short, an object is a specific comb<strong>in</strong>ation of data <strong>and</strong> the methods that can<br />

process <strong>and</strong> communicate that data. Classes def<strong>in</strong>e the types for objects; hence,<br />

objects are sometimes referred to as <strong>in</strong>stances of their def<strong>in</strong><strong>in</strong>g class, because they<br />

take on the name of that class as their type.<br />

An example def<strong>in</strong>ition of a <strong>Java</strong> class is shown <strong>in</strong> Code Fragment 1.1.<br />

Code Fragment 1.1: A Counter class for a simple<br />

counter, which can be accessed, <strong>in</strong>cremented, <strong>and</strong><br />

decremented.<br />

17

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

Saved successfully!

Ooh no, something went wrong!