In Java, strings are immutable objects. You might wonder if an object contains a String
field which can be changed to other strings, is it an immutable or mutable object?
In fact, an object is considered immutable if its state cannot be changed after it is created. This means that all fields of the object must be final and cannot be modified after the object is constructed. Even though String
objects themselves are immutable, if an object contains a field of type String
that can be changed to reference a different String
object, then the containing object is considered mutable. This is because the state of the object (i.e., the value of the String
field) can change.
Here’s an example to illustrate this:
private String mutableField; // fields without final can be changed
public MutableObject(String initialField) {
this.mutableField = initialField;
}
public void setMutableField(String newField) {
this.mutableField = newField;
}
public String getMutableField() {
return mutableField;
}
}
In this example, MutableObject
is mutable because the mutableField
can be changed using the setMutableField
method.
On the other hand, an immutable object would look like this:
private final String immutableField; // final fields cannot be changed
public ImmutableObject(String initialField) {
this.immutableField = initialField;
}
public String getImmutableField() {
return immutableField;
}
}
In this case, ImmutableObject
is immutable because the immutableField
is final
and cannot be changed after the object is created.
So, if your object allows its String
field to be changed, it is considered mutable.
沒有留言:
張貼留言