Final (Java): Difference between revisions

Content deleted Content added
No edit summary
Shagie (talk | contribs)
Final variables: Make sentence agree with reference, make code example agree with sentence.
Line 41:
A '''final [[Variable (programming)|variable]]''' can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.<ref>Java Language Specification #8.3.1.2.</ref> (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still [[mutable object|mutable]], if it was originally mutable.)
 
Unlike the value of a [[constant (computer science)|constant]], the value of a final variable is not necessarily known at compile time. It is considered good practice to represent final [[primitive type]] variablesconstants in all uppercase, using underscore to separate words.<ref>http://geosoft.no/development/javastyle.html</ref>
 
Example:
Line 50:
public static final double PI = 3.141592653589793;
 
public final double RADIUSradius;
public final double XPOSxPos;
public final double YPOSyPos;
public final double ZPOSzPos;
 
Sphere(double x, double y, double z, double r) {
RADIUSradius = r;
XPOSxPos = x;
YPOSyPos = y;
ZPOSzPos = z;
}
 
Line 66:
</source>
 
Any attempt to reassign <code>RADIUSradius</code>, <code>XPOSxPos</code>, <code>YPOSyPos</code>, or <code>ZPOSzPos</code> will meet with a compile error. In fact, even if the constructor doesn't set a final variable, attempting to set it outside the constructor will result in a compilation error.
 
To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one: