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.

• T <strong>and</strong> S are class types <strong>and</strong> S is a subclass of T<br />

• T <strong>and</strong> S are <strong>in</strong>terface types <strong>and</strong> S is a sub<strong>in</strong>terface of T<br />

• T is an <strong>in</strong>terface implemented by class S.<br />

In general, a narrow<strong>in</strong>g conversion of reference types requires an explicit cast.<br />

Also, the correctness of a narrow<strong>in</strong>g conversion may not be verifiable by the<br />

compiler. Thus, its validity should be tested by the <strong>Java</strong> run-time environment<br />

dur<strong>in</strong>g program execution.<br />

The example code fragment below shows how to use a cast to perform a<br />

narrow<strong>in</strong>g conversion from type Number to type Integer.<br />

Number n = new Integer(2); // widen<strong>in</strong>g conversion<br />

from Integer to Number<br />

Integer i = (Integer) n; // narrow<strong>in</strong>g conversion<br />

from Number to Integer<br />

In the first statement, a new object of class Integer is created <strong>and</strong> assigned to a<br />

variable n of type Number. Thus, a widen<strong>in</strong>g conversion occurs <strong>in</strong> this<br />

assignment <strong>and</strong> no cast is required. In the second statement, we assign n to a<br />

variable i of type Integer us<strong>in</strong>g a cast. This assignment is possible because n<br />

refers to an object of type Integer. However, s<strong>in</strong>ce variable n is of type<br />

Number, a narrow<strong>in</strong>g conversion occurs <strong>and</strong> the cast is necessary.<br />

Cast<strong>in</strong>g Exceptions<br />

In <strong>Java</strong>, we can cast an object reference o of type T <strong>in</strong>to a type S, provided the<br />

object o is referr<strong>in</strong>g to is actually of type S. If, on the other h<strong>and</strong>, object o is not<br />

also of type S, then attempt<strong>in</strong>g to cast o to type S will throw an exception called<br />

ClassCastException. We illustrate this rule <strong>in</strong> the follow<strong>in</strong>g code fragment:<br />

Number n;<br />

Integer i;<br />

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

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

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

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

123

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

Saved successfully!

Ooh no, something went wrong!