Java Reference
In-Depth Information
If a final field does not have an initializer it is termed a blank final. You
would use a blank final when simple initialization is not appropriate for
a field. Such fields must be initialized once the class has been initialized
(in the case of static final fields) or once an object of the class has been
fully constructed (for non-static final fields). The compiler will ensure
that this is done and refuse to compile a class if it determines that a
final field does not get initialized.
A final field of a primitive type, or of String type, that is initialized with
a constant expressionthat is, an expression whose value can be determ-
ined at compile timeis known as a constant variable. Constant variables
are special because the compiler treats them as values not fields. If your
code refers to a constant variable, the compiler does not generate byte-
code to load the value of the field from the object, it simply inserts the
value directly into the bytecode. This can be a useful optimization, but
it means that if the value of your final field needs to be changed, then
every piece of code that refers to that field also has to be recompiled.
Whether a property is immutable is determined by the semantics of the
application for which the class was designed. When you decide whether
a field should be final , consider three things:
Does the field represent an immutable property of the object?
Is the value of the field always known at the time the object is
created?
Is it always practical and appropriate to set the value of the field
when the object is created?
If the property is merely infrequently changed rather than truly immut-
able then a final field is not appropriate. If the value of the field is not
known when the object is created then it can't be made final , even if
it is logically immutable once known. For example, in a simulation of
celestial bodies a comet may become trapped by the gravitational pull
of a star and commence to orbit that star. Once trapped the comet or-
bits the star forever or until it is destroyed. In this situation the orbits
field will hold an immutable value once set, but that value is not known
 
Search WWH ::




Custom Search