Java - 可変で不変なオブジェクト

Java –可変および不変オブジェクト

この記事では、Javaの可変オブジェクトと不変オブジェクトの違いを示します

1. Mutable object –オブジェクトの作成後に状態とフィールドを変更できます。 例:StringBuilderjava.util.Dateなど。

2. Immutable object –オブジェクトの作成後は何も変更できません。 例:StringIntegerLongなどのボックス化されたプリミティブオブジェクト。

1. Javaミュータブルの例

通常、フィールド値を変更するメソッドを提供し、オブジェクトを拡張できます。

MutableExample.java

package com.example;

public class MutableExample {

    private String name;

    MutableClass(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    // this setter can modify the name
    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) {

        MutableExample obj = new MutableExample("example");
        System.out.println(obj.getName());

        // update the name, this object is mutable
        obj.setName("new example");
        System.out.println(obj.getName());

    }
}

出力

example
new example

2. Java不変の例

不変オブジェクトを作成するには、クラスをfinalにし、フィールドを変更するメソッドを提供しません。

ImmutableExample.java

package com.example;

// make this class final, no one can extend this class
public final class ImmutableExample {

    private String name;

    ImmutableExample (String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    //no setter

    public static void main(String[] args) {

        ImmutableExample obj = new ImmutableExample("example");
        System.out.println(obj.getName());

        // there is no way to update the name after the object is created.
        // obj.setName("new example");
        // System.out.println(obj.getName());

    }
}

出力

example

Note
不変オブジェクトは単純で、スレッドセーフ(同期の必要がない)であり、エラーが発生しにくく、より安全です。 可能であれば、すべてのオブジェクトを不変にします。

P.S Please refer to the Effective Java Book – Item 15: Minimize mutability.