Whether the object being mutable is stationary

If I have an object, 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);

      

Since I can still change the age, is it not considered permanent?

+3


source to share


4 answers


Since I can still change the age, is it not considered permanent?



PERSON

is "constant" because it always points to the same instance PERSON

. However, the instance PERSON

it points to is not permanent, as it can be mutated. This is more a question of terminology than anything.

+5


source


It is a reference final

(constant), but you can update its state (instance variable), but you cannot assign it to another Person object.

This is better explained under JLS - 4.12.4. final variables

Once the final variable has been assigned, it always contains the same value.

If the final variable contains an a reference

for an object, then the state of the object can be changed using operations on the object, but the variable will always refer to the same object.



You cannot tell

person = new Person(20);

      

+3


source


Think about it like in real life. The PERSON that you create is a specific person. You can tag it with PERSON , user2896769 or with a unique ID . When you refer to an object by this label, you are always referring to the same object (because it is final), but the object itself can change (as people can actually get older, so their age changes).

So, final

means that the reference is a constant, not that the object itself is immutable . If you want your PERSONAL not to change at all, the link must be final

, and the object the referenced object is must be immutable .

When you write:

public static final Person PERSON = new Person(12);

      

This means that PERSON will now refer to the newly created human object. It does not mean that PERSONthe newly created person object. Again - means that it refers to (points to) an object. So you have an object reference. And this link is final, permanent, always pointing to the same object. But the object itself can change while it is changed.

0


source


I guess it is a matter of semantics whether PERSON is constant, but it is not considered a "constant", but rather an end object reference.

Also, I would go with the normal undername for the variable. There's a great discussion of this in this question .

One of the answers in the referenced question quotes Effective Java, 2nd edition for the following criteria for a constant field:

A constant field is a static final field whose value is unchanged. If the static final field is of a primitive type or an immutable reference type (...), then it is a constant field.

0


source







All Articles