
不可变类是指其实例在创建后就无法修改的类。这对于创建线程安全应用程序和确保数据完整性非常有用。
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中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号