class 的不可变性正在被破坏,如何防止这种情况发生?

Immutability of the class is getting destroyed how to prevent that?

我有学生 class 我有最终变量而且我有 变量 'doj' 是 Date 类型,我已经为 他们,但是在 main class 中,我能够更新变量 doj 破坏了不变性 property.How 我可以阻止它吗?

代码如下:

final public class Student {
    final String name;
    final String rollno;
    final Date dob; 

    public Student(String name, String rollno, Date dob) {
        super();
        this.name = name;
        this.rollno = rollno;
        this.dob = dob;
    }

    public final String getName() {
        return name;
    }

    public final String getRollno() {
        return rollno;
    }

    public final Date getDob() {
        return dob;
    }

}

public class StudentMain {

    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws InterruptedException {
        Student s=new Student("john", "1", new Date());
        System.out.println(s.getDob());
        Date d=s.getDob();
        d.setDate(30072019);
        System.out.println(s.getName());
        System.out.println(s.getRollno());
        System.out.println(s.getDob());
    }

}

你必须像这样使用构造函数。

public Student(String name, String rollno, Date dob) {
        super();
        this.name = name;
        this.rollno = rollno;
        this.dob = new Date(dob.getTime());
    }

在getter方法的情况下,你必须这样使用。

public final Date getDob() {
        return new Date(dob.getTime());
    }

由于 Date 是可变对象,您应该在构造函数中创建一个新的 Date 对象:

public Student(String name, String rollno, Date dob) {
            super();
            this.name = name;
            this.rollno = rollno;
            this.dob = new Date(dob.getTime());
}

但是 java.util.Date class 已弃用,您应该考虑使用 LocalDate or LocalDateTime - 这两个 class 都是不可变的。

您需要 return 内部(不可变)状态的副本。您不应该公开内部引用。

例如:

public final Date getDob() {
    return new Date(dob.getTime());
}