
在 java 中创建不可变类
不可变类是指其实例在创建后就无法修改的类。这对于创建线程安全应用程序和确保数据完整性非常有用。
不可变类的关键特征
- 所有字段都是私有且最终的。
- 未提供 setter 方法。
- 字段的初始化是通过构造函数进行的。
- 必要时返回可变对象的防御副本。
不可变类的示例
public final class immutablepoint {
private final int x;
private final int y;
public immutablepoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getx() {
return x;
}
public int gety() {
return y;
}
// example of returning a new instance instead of modifying the current one
public immutablepoint move(int deltax, int deltay) {
return new immutablepoint(this.x + deltax, this.y + deltay);
}
}
使用示例
public class Main {
public static void main(String[] args) {
ImmutablePoint point1 = new ImmutablePoint(1, 2);
System.out.println("Point1: (" + point1.getX() + ", " + point1.getY() + ")");
// Moving the point creates a new instance
ImmutablePoint point2 = point1.move(3, 4);
System.out.println("Point2: (" + point2.getX() + ", " + point2.getY() + ")");
System.out.println("Point1 remains unchanged: (" + point1.getX() + ", " + point1.getY() + ")");
}
}
结论
在 java 中创建不可变类涉及定义一个具有 final 字段且没有 setter 方法的类。这确保了对象一旦创建,其状态就无法更改。使用不可变类可以生成更安全、更可预测的代码,尤其是在并发编程场景中。











