is an object with a string field mutable or immutable

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:

public class MutableObject {
    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:

public final class ImmutableObject {
    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.

沒有留言:

Installing Code::Blocks on Windows for APCS Preparation

APCS 為大學程式設計先修檢測 (Advanced Placement Computer Science),其檢測等級可供大學個人申請入學之用。各電腦相關科系APCS組都明訂要求的檢測等級,須符合其門檻才具備申請資格。其中,針對 C 及 C++ 程式檢測,考場提供 Linux...

總網頁瀏覽量