14.07.2013 Views

Contents - Cultural View

Contents - Cultural View

Contents - Cultural View

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.

final (Java) 121<br />

}<br />

Sphere(double x, double y, double z, double r) {<br />

}<br />

[...]<br />

radius = r;<br />

xpos = x;<br />

ypos = y;<br />

zpos = z;<br />

Any attempt to reassign radius, xpos, ypos, zpos will meet with a compile error. In fact, even if the constructor<br />

doesn't set a final variable, attempting to set it outside the constructor will result in a compile error.<br />

To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a<br />

single one:<br />

public final Position pos;<br />

where pos is an object with three properties pos.x, pos.y and pos.z. Then pos cannot be assigned to, but the three<br />

properties can, unless they are final themselves.<br />

Like full immutability, finality of variables has great advantages, especially in optimization. For instance, Sphere<br />

will probably have a function returning its volume; knowing that its radius is constant allows us to memoize the<br />

computed volume. If we have relatively few Spheres and we need their volumes very often, the performance gain<br />

might be substantial. Making the radius of a Sphere final informs developers and compilers that this sort of<br />

optimization is possible in all code that uses Spheres.<br />

Blank final<br />

The blank final, which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer. [4] [5] A<br />

blank final can only be assigned to once and it must be definitely unassigned when an assignment occurs. In order to<br />

do this, a Java compiler runs a flow analysis to ensure that, for every assignment to a blank final variable, the<br />

variable is definitely unassigned before the assignment; otherwise a compile-time error must occur. [6]<br />

In general, a Java compiler will ensure that the blank final is not used until is assigned a value and that once assigned<br />

a value, the now final variable cannot be reassigned another value. [7]<br />

Difference from the C++ "const" type qualifier<br />

• In C++, a const field is not only protected from being reassigned, but there is the additional limitation that only<br />

const methods can be called on it and it can only be passed as the const argument of other methods.<br />

• Non-static inner classes can freely access any field of the enclosing class, final or not.<br />

External links<br />

• Its Time To Deprecate Final [8]<br />

• The Final Word On the final Keyword by Renaud Waldura [9]

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

Saved successfully!

Ooh no, something went wrong!