创建不可变的Java对象 [英] Make immutable Java object

查看:127
本文介绍了创建不可变的Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是使Java对象不可变。我有一个班级学生。我用以下方式对其进行编码以实现不变性:

My goal is to make a Java object immutable. I have a class Student. I coded it in the following way to achieve immutability:

public final class Student {

private String name;
private String age;

public Student(String name, String age) {
    this.name = name;
    this.age = age;
}

public String getName() {
    return name;
}

public String getAge() {
    return age;
}

}

我的问题是,什么是实现学生课程的不变性的最佳方法?

My question is, what is the best way to achieve immutability for the Student class?

推荐答案

严格来说,你的类不是一成不变的,它只是有效的一成不变的。要使其不可变,您需要使用 final

Your class is not immutable strictly speaking, it is only effectively immutable. To make it immutable, you need to use final:

private final String name;
private final String age;

虽然差异可能看似微妙,但它可以在多线程上下文中产生重大影响。不可变类本质上是线程安全的,只有在安全发布时,有效不可变类才是线程安全的。

Although the difference might seem subtle, it can make a significant difference in a multi-threaded context. An immutable class is inherently thread-safe, an effectively immutable class is thread safe only if it is safely published.

这篇关于创建不可变的Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆