10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

8.4.8 Inheritance, Overriding, and Hiding CLASSES<br />

226<br />

DISCUSSION<br />

<strong>The</strong> rules above allow for covariant return types - refining the return type of a method when<br />

overriding it.<br />

For example, the following declarations are legal although they were illegal in prior versions<br />

of the <strong>Java</strong> programming language:<br />

class C implements Cloneable {<br />

C copy() { return (C)clone(); }<br />

}<br />

class D extends C implements Cloneable {<br />

D copy() { return (D)clone(); }<br />

}<br />

<strong>The</strong> relaxed rule for overriding also allows one to relax the conditions on abstract<br />

classes implementing interfaces.<br />

DISCUSSION<br />

Consider<br />

class StringSorter {<br />

// takes a collection of strings and converts it to a sortedlist<br />

List toList(Collection c) {...}<br />

}<br />

and assume that someone subclasses StringCollector<br />

class Overrider extends StringSorter{<br />

List toList(Collection c) {...}<br />

}<br />

Now, at some point the author of StringSorter decides to generify the code<br />

class StringSorter {<br />

// takes a collection of strings and converts it to a list<br />

List toList(Collection c) {...}<br />

}<br />

An unchecked warning would be given when compiling Overrider against the new<br />

definition of StringSorter because the return type of Overrider.toList() is List,<br />

which is not a subtype of the return type of the overridden method, List

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

Saved successfully!

Ooh no, something went wrong!