Reputation:
In the below code i am assigning data to final object .But not getting the compile error .
class Name {
private String name;
public Name (String s) {
this.name = s;
}
public void setName(String s) {
this.name = s;
}
}
private void test (final Name n) {
n.setName("test");//here exception coming but not giving compile error
}
Upvotes: 3
Views: 72
Reputation: 124225
From Java Language Specification:
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.
So it is OK to manipulate state of object pointed by n
private void test(final Name n) {
n.setName("test");
}
but you can't make n
to store another object
private void test(final Name n) {
n = new Name("test"); //Can't do this
}
Upvotes: 5
Reputation: 272497
Because final
applies to the reference n
, not the object that n
refers to.
So you won't be able to do this:
n = new Name("test");
Upvotes: 6