Content deleted Content added
Line 31:
Example:
<source lang="java">
public static final double PI = 3.141592653589793; // this might as well be a constant
▲ public class Sphere {
▲ public final double ypos;
Sphere(double x, double y, double z, double r) {▼
radius = r;▼
xpos = x;▼
ypos = y;▼
zpos = z;▼
}▼
[...]▼
}▼
</source>
Immutability of variables has great advantages, especially in optimization. For instance, Sphere 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 Spheres and we need their volumes very often, the gain might be substantial. Making the radius of a Sphere final informs developers and compilers that this sort of optimization is possible in all code that uses Spheres.
|