Final (Java): Difference between revisions

Content deleted Content added
Final variables: Replaced wrong and inaccurate statements about final variables with correct and precise statements and good code example
Final variables in nested objects: rewrote the intro paragraph since it didn't make a clear distinction between final and immutable
Line 97:
=== Final variables in nested objects ===
 
When finalFinal variables containcan referencesbe used to otherconstruct trees of immutable objects. Once constructed, these objects are typicallyguaranteed requirednot to bechange anymore. To achieve this, an immutable class must only have final fields, tooand these final fields may only have immutable types themselves. Java's primitive types are immutable, as are strings and several other classes.

If thisthe above construction is notviolated by having an object in the casetree that is not immutable, the expectation does not hold that anything reachable via the final variable is constant. For example, the following code defines a coordinate system whose origin should always be at (0, 0). The origin is implemented using a <code>java.awt.Point</code> though, and this class defines its fields as public and modifiable. This means that even when reaching the <code>origin</code> object over an access path with only final variables, that object can still be modified, as the below example code demonstrates.
 
<source lang="java">