Final (Java): Difference between revisions

Content deleted Content added
SAE1962 (talk | contribs)
m Final methods: Link stated more precisely. Small corrections done.
SAE1962 (talk | contribs)
m Final variables: Link stated more precisely. Small corrections done.
Line 27:
= Final variables =
 
A '''final [[variable]]''' is [[Immutable object|immutable]], i. e. Itit can only be assigned to once. If the variable is a field of a class, it must be assigned to in the constructor of its class. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.)
 
Unlike the value of a [[constant (computer science)|constant]], the value of a final variable is not necessarily known at compile time.
Line 51:
}
</source>
Immutability of variables has great advantages, especially in optimization. For instance, <code>Sphere</code> will probably have a function returning its volume; knowing that its radius is constant allows us to [[memoize]] the computed volume. If we have relatively few Spheres<code>Sphere</code>s and we need their volumes very often, the gain might be substantial. Making the radius of a <code>Sphere</code> <code>final</code> informs developers and compilers that this sort of optimization is possible in all code that uses Spheres<code>Sphere</code>s.
 
[[Category:Java programming language]]