Final (Java): Difference between revisions

Content deleted Content added
Line 31:
 
Example:
<source lang="java">
public class Sphere {
 
public static final double PI = 3.141592653589793; // this might as well be a constant
public class Sphere {
public final double yposradius;
public static final double PI = 3.141592653589793xpos; // this might as well be a constant
public final double radiusypos;
public final double xposzpos;
public final double ypos;
public final double zpos;
Sphere(double x, double y, double z, double r) {
radius = r;
xpos = x;
ypos = y;
zpos = z;
}
[...]
}
 
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.