Java Reference
In-Depth Information
If a final variable holds a reference to an object, then the state of the object may be
changed by operations on the object, but the variable will always refer to the same
object.
This also applies to arrays, because arrays are objects; if a final variable holds a ref-
erencetoanarray,thenthecomponentsofthearraymaystillbechangedbyoperationson
the array, but the variable will always refer to the same array.
Similarly, a final method parameter obtains an immutable copy of the object referen-
ce . Again, this has no effect on the mutability of the referenced data.
Noncompliant Code Example (Mutable Class, final Reference)
In this noncompliant code example, the programmer has declared the reference to the
point instance to be final under the incorrect assumption that doing so prevents modi-
ficationofthe values oftheinstancevariables x and y .Thevaluesoftheinstancevariables
can be changed after their initialization because the final clause applies only to the ref-
erence to the point instance and not to the referenced object.
Click here to view code image
class Point {
private int x;
private int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
void set_xy(int x, int y) {
this.x = x;
this.y = y;
}
void print_xy() {
System.out.println("the value x is: " + this.x);
System.out.println("the value y is: " + this.y);
}
}
public class PointCaller {
public static void main(String[] args) {
final Point point = new Point(1, 2);
point.print_xy();
Search WWH ::




Custom Search