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.

object (assum<strong>in</strong>g we are allowed access to those<br />

variables).<br />

Variable Modifiers<br />

In some cases, we may not be allowed to directly access some of the <strong>in</strong>stance<br />

variables for an object. For example, an <strong>in</strong>stance variable declared as private <strong>in</strong><br />

some class is only accessible by the methods def<strong>in</strong>ed <strong>in</strong>side that class. Such<br />

<strong>in</strong>stance variables are similar to device parameters that cannot be accessed<br />

directly from a remote control. For example, some devices have <strong>in</strong>ternal<br />

parameters that can only be read or assigned by a factory technician (<strong>and</strong> a user is<br />

not allowed to change those parameters without violat<strong>in</strong>g the device's warranty).<br />

When we declare an <strong>in</strong>stance variable, we can optionally def<strong>in</strong>e such a variable<br />

modifier, follow that by the variable's type <strong>and</strong> the identifier we are go<strong>in</strong>g to use<br />

for that variable. Additionally, we can optionally assign an <strong>in</strong>itial value to the<br />

variable (us<strong>in</strong>g the assignment operator ("="). The rules for a variable name are<br />

the same as any other <strong>Java</strong> identifier. The variable type parameter can be either a<br />

base type, <strong>in</strong>dicat<strong>in</strong>g that this variable stores values of this type, or a class name,<br />

<strong>in</strong>dicat<strong>in</strong>g that this variable is a reference to an object from this class. F<strong>in</strong>ally, the<br />

optional <strong>in</strong>itial value we might assign to an <strong>in</strong>stance variable must match the<br />

variable's type. For example, we could def<strong>in</strong>e a Gnome class, which conta<strong>in</strong>s<br />

several def<strong>in</strong>itions of <strong>in</strong>stance variables, shown <strong>in</strong> <strong>in</strong> Code Fragment 1.3.<br />

31

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

Saved successfully!

Ooh no, something went wrong!