What is an immutable object? How to create an immutable object in Java?

 An immutable object is an object whose state cannot be modified or changed once created. In Java, immutable objects have the following characteristics:

  1. State Immunity: The property value of an object cannot be modified.

  2. Thread Safety: Since the state of an immutable object cannot be changed, no additional synchronization measures are required for multi-threaded access, so it is thread safe.

  3. Security (Security): The value of an immutable object cannot be maliciously modified, so it is suitable for security-sensitive contexts.

  4. Reusability: Since the state of immutable objects remains unchanged, they can be used multiple times without worrying about side effects.

  To create an immutable object, several steps need to be taken:

  1. Make the class declaration final

  By declaring a class final, other classes are prevented from inheriting it, thereby preventing subclasses from modifying its state.

  2. Declare properties as private and final

  Make sure that the property cannot be directly accessed by the outside world and cannot be modified once assigned.

  3. Does not provide a method to modify the state

  Do not provide methods that modify the state of the object, including setter methods.

  4. Provide read-only methods

  Provide methods to get the object's property values, but do not provide methods to modify property values.

  Here is an example showing how to create an immutable Java class:

public final class ImmutablePerson {
    private final String name;
    private final int age;

    public ImmutablePerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

  In this example, the ImmutablePerson class has two private final properties that can only be initialized in the constructor, and no method is provided to modify them. Therefore, ImmutablePerson is an immutable object whose state cannot be modified once created.

  By following the above pattern, we can create immutable objects which helps in ensuring the maintainability, thread safety and security of the code.

Guess you like

Origin blog.csdn.net/Blue92120/article/details/132445039