If i have an object lets say for example
public class Person {
private int age;
public Person(int age) {
this.age = age;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
and
public static final Person PERSON = new Person(12);
Because I still can change the age is it not considered constant?
Because I still can change the age is it not considered constant?
PERSON is "constant" in that it will always point to the same Person instance. The Person instance to which it does point, however, is not constant since it can be mutated. This is more a matter of terminology than anything.
It's reference that is final(constant) but still you can update its state (instance variable) but you can't assign it to other Person object.
It's better explanaied under JLS - 4.12.4. final Variables
Once a final variable has been assigned, it always contains the same value.
If a final variable holds a
referenceto 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.
You can't say
person = new Person(20);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With