Java Reference
In-Depth Information
Because program state changes all the time, you might be tempted to think that immutable
objects are of limited use, but this is not the case. There is a difference between an object
being immutable and the reference to it being immutable. Program state stored in immutable
objects can still be updated by “replacing” immutable objects with a new instance holding
new state; the next section offers an example of this technique. [13]
3.4.1. Final Fields
The final keyword, a more limited version of the const mechanism from C++, supports
the construction of immutable objects. Final fields can't be modified (although the objects
they refer to can be modified if they are mutable), but they also have special semantics under
the Java Memory Model. It is the use of final fields that makes possible the guarantee of ini-
tializationsafety (see Section 3.5.2 ) that lets immutable objects be freely accessed and shared
without synchronization.
Even if an object is mutable, making some fields final can still simplify reasoning about
its state, since limiting the mutability of an object restricts its set of possible states. An object
that is “mostly immutable” but has one or two mutable state variables is still simpler than one
that has many mutable variables. Declaring fields final also documents to maintainers that
these fields are not expected to change.
Search WWH ::




Custom Search