[Java] Create immutable class with JAVA

1 minute read

What is imutable

Immutable is immutable. In other words, immutable classes are classes whose instance contents do not change (= cannot be rewritten). Rewriting an immudatable class means recreating an instance (old instances accumulate when multiple instances are created in the iteration process, and the processing speed slows down, so be careful when using it. Must be done). When using immutable class, it is necessary to check whether the contents have been changed or whether reference type values are used.

Immutable benefits

Since the state of immutable objects does not change from the time of creation, there is no concern that the value will change in an unintended form during processing. A typical immutable class is the String class.

Conditions when creating

In order to create immutable class, the following four conditions must be met.

1. Declare class as final

2. Make all fields final and private Declare class as final or make constructor private and instantiate with factory method

3.setter is not defined Declare class as final or make constructor private and instantiate with factory method

4. The field does not contain a reference to an Mmutable object

Fruits.java


public final class Fruits {
    private final String color;
    private final int amount;

    public Fruits(String name, String, int age) {
        this.name = color;
        this.age = amount;
    }

    public String getColor() {
        return color;
    }

    public int getAmount() {
        return amount;
    }
}

Attempting to change it will result in an error.

FruitsTest.java


@Test
public void fruitsTest() {
    final Person Fruits = new Fruits("Red", 28);
    // error
    // fruits.setColor("yellow");
    // fruits.amount(30);
}

Tags:

Updated: