在 Java 中,**不可变类(Immutable Class)**指的是:对象一旦创建,其状态(字段值)就不能被修改。实现不可变类通常遵循以下规范和步骤:
final 修饰防止被继承,从而避免子类破坏不可变性。
public final class Person {
}
private final 修饰private:外部不能直接访问final:赋值后不能修改private final String name;
private final int age;
只提供 getter(或根本不提供可变访问)
public String getName() {
return name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
Date、List)必须防御性拷贝(Defensive Copy),防止外部修改影响内部状态。
private final Date birthDate;
public Person(Date birthDate) {
this.birthDate = birthDate; // 外部仍可修改
}
public Person(Date birthDate) {
this.birthDate = new Date(birthDate.getTime());
}
public Date getBirthDate() {
return new Date(birthDate.getTime());
}
private final List<String> hobbies;
public List<String> getHobbies() {
return Collections.unmodifiableList(hobbies);
}
或使用 Java 9+:
List.copyOf(hobbies);
import java.util.Date;
import java.util.List;
public final class User {
private final String name;
private final int age;
private final Date birthDate;
private final List<String> roles;
public User(String name, int age, Date birthDate, List<String> roles) {
this.name = name;
this.age = age;
this.birthDate = new Date(birthDate.getTime());
this.roles = List.copyOf(roles);
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Date getBirthDate() {
return new Date(birthDate.getTime());
}
public List<String> getRoles() {
return roles;
}
}
HashMap 的 keyStringInteger、Long 等包装类BigDecimalLocalDate、LocalDateTime如果你愿意,我也可以讲:
record(Java 14+)如何实现不可变免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。