不可变类是其实例在创建后就无法修改的类。这对于创建线程安全应用程序和确保数据完整性非常有用。
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 方法的类。这确保了对象一旦创建,其状态就无法更改。使用不可变类可以生成更安全、更可预测的代码,尤其是在并发编程场景中。
以上是如何在java中创建不可变类?举例说明的详细内容。更多信息请关注PHP中文网其他相关文章!