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.

沒有留言:

how to install and use Jeddict AI Assistant on NetBeans IDE 23+

Jeddict AI Assistant  為適用於  NetBeans IDE 23 以上版本的插件,能夠連接大語言模型,協助編寫程式碼,大幅提升開發體驗,讓程式撰寫更輕鬆、更智慧。以下簡介其安裝方法及功能。 A.安裝與解除安裝 安裝步驟: ...

總網頁瀏覽量