Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this object mutable?

Tags:

java

mutable

If I have a class like that:

public class MyObject {
    private int myField = 2;
    public void setMyField(int f) {
        this.myField = f;
    }
}

Will objects of this class be mutable? Thanks!

like image 658
Roman Avatar asked Jan 27 '14 10:01

Roman


4 Answers

Of course - if you want it to be immutable, then you need something like:

public class MyObject {
    private final int myField;

    public MyObject(int f) {
      myfield = f;
    }

    public int getMyField() {
        return myField;
    }
}
like image 141
Jakub Kubrynski Avatar answered Oct 01 '22 15:10

Jakub Kubrynski


yes

Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.

like image 33
venergiac Avatar answered Oct 01 '22 13:10

venergiac


You already have several answers with a "Yes".

I would like to add a "but" (if I would be bold, I would say "No" ;-)

Yes, an object of this class appears to be mutable, since it provides a setter to change the field. However, since it does not have a getter for that field, neither any other getter depending on that field, and since the field is private, it is currently not possible to read that state.

Put differently: The object has state, but it does not expose any state to the outside.

I would call that object "effectively immutable".

There are some design patterns, where objects are "effectively immutable", for example "Lazy Initialization" of an "Immutable Object".

Note: The concept of being "effectively immutable" is discussed in Section 3.5.4 of Java Concurrency in Practice by Brian Goetz.

like image 31
Christian Fries Avatar answered Oct 01 '22 15:10

Christian Fries


Yes, objects of this class are mutable. The designer of the class can't prohibit by any technical means (in real existing Java) consumers of the objects to observe and modify the contents of the field.

private is an explicitly declared contract regarding intended usage of the field - this contract can be broken, e.g. with reflection.

Not providing any methods that change the data of an object after creation can also be a (implicitly declared) contract about intended use and mutability - this contract, too, can be broken, like any contract that needs two conforming parties.

Edit: Unless there is another party that has the means to enforce - like in Java the SecurityManager stopping you from changing a final field at runtime.

like image 38
Oliver Schweitzer Avatar answered Oct 01 '22 13:10

Oliver Schweitzer