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