Content deleted Content added
RolandIllig (talk | contribs) →Final variables: Replaced wrong and inaccurate statements about final variables with correct and precise statements and good code example |
|||
Line 95:
Since the obj variable goes out of scope with each iteration of the loop, it is actually redeclared each iteration, allowing the same token (i.e. <code>obj</code>) to be used to represent multiple variables.<ref>{{cite web|url=http://www.cs.cmu.edu/~pattis/15-1XX/15-200/lectures/morejava/lecture.html|title=More Java|last=Pattis|first=Richard E.|work=Advanced Programming/Practicum 15–200|publisher=School of Computer Science [[Carnegie Mellon University]]|accessdate=23 July 2010}}</ref>
=== Final variables in nested objects ===
When final variables contain references to other objects, these objects are typically required to be immutable, too. If this is not the case, 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">
▲import java.sql.Date;
static class CoordinateSystem {
private final Point origin = new Point(0, 0);
public Point getOrigin() { return origin; }
}
public static void main(String[] args) {
CoordinateSystem coordinateSystem = new CoordinateSystem();
coordinateSystem.getOrigin().x = 15;
assert coordinateSystem.getOrigin().getX() == 0;
}
}
</source>
The reason for this is that declaring a variable final only
To prevent this undesirable situation, a common requirement is that all fields of an immutable object must be final, and that the types of these fields must be immutable themselves. This disqualifies <code>java.util.Date</code> and <code>java.awt.Point</code> and several other classes from being used in such immutable objects.
===Final and inner classes===
|