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

标签 java immutability

我有一个 Student 类,其中有最终变量,并且我有 变量“doj”是日期类型,我已经提供了 setter/getter 他们,但在主类中我可以更新变量 doj 破坏了不变性属性。我怎样才能防止这种情况发生?

下面是代码:

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());
    }

关于java - 类的不变性正在被破坏,如何防止这种情况发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57063635/

相关文章:

java - 使用 Ant 编译

c# - 我可以让字符串表现得像引用类型吗?

java - 如何在 Clojure 中使 Java 类不可变?

java - 了解了 Dao 模式,它可以用于从缓存中检索数据吗?

java - 加密的 AES key 太大,无法使用 RSA (Java) 解密

java - 为什么 java8 服务器 JRE 不包含服务器特定工具,如 jstack、jmap、jvisualvm、jstat

java - 显示在 Android 中按下按钮后耗时

c# - 当方法采用对象 C# 时,字符串作为引用参数的问题

F# 不变性、纯函数和副作用

performance - 为什么 PostgreSQL 多次调用我的 STABLE/IMMUTABLE 函数?