我有一个 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/