Content deleted Content added
m robot Adding: uk:Final (Java) |
No edit summary |
||
Line 2:
In the [[Java (programming language)|Java programming language]], the <code>'''final'''</code> [[Keyword (computing)|keyword]] is used in several different contexts to define an entity which cannot later be changed.
== Concept ==
A final variable in Java can be assigned to only once, but if the variable is a reference-type, you can still change what it refers to. A variable can be declared final. A final variable may only be assigned to once. It is a compile time error if a final variable is assigned to unless it is definitely unassigned immediately prior to the assignment.A blank final is a final variable whose declaration lacks an initializer. Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object. This applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.
Declaring local variables as final could sometimes have advantages like: -
1. Allows compiler to detect unintentional modification of a variable that is supposed to be constant
2. May allow Java compiler or Just In Time compiler to optimise code, knowing that the variable value will not change. This might give a small performance gain in a few circumstances.
3. May help maintenance of the program, by making it clear to the maintainer that the variable should not change.
== Final classes ==
Line 50 ⟶ 56:
[...]
}
</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 <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 <code>Sphere</code>s.
|