Content deleted Content added
use of final keyword on classes and methods is not for efficiency |
m I am not a Java programmer so I had to verify this by using Google. To my surprise none of the introduction of final variables that I found mention that final variables. So please douclecheck this |
||
Line 20:
A common misconception is that declaring a class or method final improves efficiency by allowing the compiler to directly insert the method inline where ever it is called. This is not completely true; the compiler is unable to do this because the classes loaded at runtime might not be same versions of the ones that were just compiled. Further, the runtime environment and [[JIT]] compiler have the information about exactly what classes have been loaded, and are able to make better decisions about when to inline, whether or not the method is final.[http://www.ibm.com/developerworks/java/library/j-jtp1029.html]
A '''final [[variable]]''' is [[immutable]]. It can only be assigned to once, in the constructor of its class.
Example:
public class
public static final double PI = 3.141592653589793; // this might as well be a constant
public final double radius;
public final double xpos;
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;
}
[...]
}
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 value of the sphere. 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.
[[Category:Java programming language]]
|