Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a mutable object still constant

Tags:

java

constants

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?

like image 934
user2896769 Avatar asked Jun 02 '26 23:06

user2896769


2 Answers

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.

like image 104
arshajii Avatar answered Jun 04 '26 12:06

arshajii


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 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.

You can't say

person = new Person(20);
like image 35
Braj Avatar answered Jun 04 '26 12:06

Braj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!