Immutable means ** immutable **. In other words, an immutable class is a class whose instance contents do not change (= cannot be rewritten). Rewriting an immudatable class means recreating an instance (be careful when using it because old instances will accumulate and the processing speed will slow down if instances are created many times during iterative processing. I have to). When using an immutable class, it is necessary to check whether the contents have been changed and whether the reference type value is used.
Since the state of immutable objects does not change from the time of creation, there is no concern that the value will change unintentionally during processing. A typical immutable class is the String class.
To create an immutable class, the following four conditions must be met.
** 1. Declare the class as final **
** 2. Make all fields final and private ** Declare the class as final, or make the constructor private and instantiate it with a factory method
** 3. Do not define setter ** Declare the class as final, or make the constructor private and instantiate it with a factory method
** 4. The field does not contain a reference to a 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 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);
}
Recommended Posts