Thursday 26 January 2012

Final Reference Variables in Java

If the final 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, if it was originally mutable.See the example given below


class Rectangle {
Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
int length;
int breadth;
}
public class Main {
public static void main(String[] args) {
final Rectangle rect = new Rectangle(10, 5);
rect.length = 20; //Valid,can change the state of object
rect.breadth = 10; //Valid,can change the state of object
rect = new Rectangle(30, 20);// Invalid,final variable can't be reassigned.

}
}
Please listen one point that


final != immutable object

Final and immutable are not the same thing.final just means the reference can't be changed. You can't reassign INSTANCE to another reference if it's declared as final. The internal state of the object is still mutable.Immutable means that the object itself cannot be modified. An example of this is the java.lang.String class. You cannot modify the value of a string.

In the above example,to make the Rectangle immutable,declare both instance variables length and breadth itself as final. i.e.

class Rectangle {
Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
final int length;
final int breadth;
}
public class Main {

public static void main(String[] args) {
final Rectangle rect = new Rectangle(10, 5);
rect.length = 20; //Invalid,final variable can't be reassigned.
rect.breadth = 10; //Invalid,final variable can't be reassigned.
rect = new Rectangle(30, 20);// Invalid,final variable can't be reassigned.

}
}


Summary

Once a final variable has been assigned, it always contains the same value. 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 applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.

No comments:

Post a Comment