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.

In this example, notice that the class def<strong>in</strong>ition is delimited by braces, that is, it<br />

beg<strong>in</strong>s with a "{" <strong>and</strong> ends with a "} ". In <strong>Java</strong>, any set of statements between the<br />

braces "{" <strong>and</strong> "}" def<strong>in</strong>e a program block.<br />

As with the Universe class, the Counter class is public, which means that any other<br />

class can create <strong>and</strong> use a Counter object. The Counter has one <strong>in</strong>stance variable—<br />

an <strong>in</strong>teger called count. This variable is <strong>in</strong>itialized to 0 <strong>in</strong> the constructor method,<br />

Counter, which is called when we wish to create a new Counter object (this method<br />

always has the same name as the class it belongs to). This class also has one<br />

accessor method, getCount, which returns the current value of the counter. F<strong>in</strong>ally,<br />

this class has two update methods—a method, <strong>in</strong>crementCount, which <strong>in</strong>crements<br />

the counter, <strong>and</strong> a method, decrementCount, which decrements the counter.<br />

Admittedly, this is a pretty bor<strong>in</strong>g class, but at least it shows us the syntax <strong>and</strong><br />

structure of a <strong>Java</strong> class. It also shows us that a <strong>Java</strong> class does not have to have a<br />

ma<strong>in</strong> method (but such a class can do noth<strong>in</strong>g by itself).<br />

The name of a class, method, or variable <strong>in</strong> <strong>Java</strong> is called an identifier, which can be<br />

any str<strong>in</strong>g of characters as long as it beg<strong>in</strong>s with a letter <strong>and</strong> consists of letters,<br />

numbers, <strong>and</strong> underscore characters (where "letter" <strong>and</strong> "number" can be from any<br />

written language def<strong>in</strong>ed <strong>in</strong> the Unicode character set). We list the exceptions to<br />

this general rule for <strong>Java</strong> identifiers <strong>in</strong> Table 1.1.<br />

Table 1.1: A list<strong>in</strong>g of the reserved words <strong>in</strong> <strong>Java</strong>.<br />

These names cannot be used as method or variable<br />

names <strong>in</strong> <strong>Java</strong>.<br />

Reserved Words<br />

abstract<br />

18

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

Saved successfully!

Ooh no, something went wrong!