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.

To avoid problems such as this <strong>and</strong> to avoid pepper<strong>in</strong>g our code with trycatch<br />

blocks every time we perform a cast, <strong>Java</strong> provides a way to make sure an<br />

object cast will be correct. Namely, it provides an operator, <strong>in</strong>stanceof, that<br />

allows us to test whether an object variable is referr<strong>in</strong>g to an object of a certa<strong>in</strong><br />

class (or implement<strong>in</strong>g a certa<strong>in</strong> <strong>in</strong>terface). The syntax for us<strong>in</strong>g this operator is<br />

object reference<strong>in</strong>stanceof reference_type, where object_reference is an<br />

expression that evaluates to an object reference <strong>and</strong> reference_type is the name of<br />

some exist<strong>in</strong>g class, <strong>in</strong>terface, or enum (Section 1.1.3). If object_reference is<br />

<strong>in</strong>deed an <strong>in</strong>stance of reference_type, then the expression above returns true.<br />

Otherwise, it returns false. Thus, we can avoid a ClassCastException<br />

from be<strong>in</strong>g thrown <strong>in</strong> the code fragment above by modify<strong>in</strong>g it as follows:<br />

Number n;<br />

Integer i;<br />

n = new Integer(3);<br />

if (n <strong>in</strong>stanceof Integer)<br />

i = (Integer) n; // This is legal<br />

n = new Double(3.1415);<br />

if (n <strong>in</strong>stanceof Integer)<br />

i = (Integer) n; // This will not be attempted<br />

Cast<strong>in</strong>g with Interfaces<br />

Interfaces allow us to enforce that objects implement certa<strong>in</strong> methods, but us<strong>in</strong>g<br />

<strong>in</strong>terface variables with concrete objects sometimes requires cast<strong>in</strong>g. Suppose we<br />

declare a Person <strong>in</strong>terface as shown <strong>in</strong> Code Fragment 2.12. Note that method<br />

equalTo of the Person <strong>in</strong>terface takes one parameter of type Person. Thus, we<br />

can pass an object of any class implement<strong>in</strong>g the Person <strong>in</strong>terface to this<br />

method.<br />

Code Fragment 2.12 : Interface Person.<br />

124

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

Saved successfully!

Ooh no, something went wrong!