我有一个学生班,在那里我有最终变量,我有 日期类型的变量“ doj”,我已经为 他们,但是在主类中,我能够更新变量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());
}
}
答案 0 :(得分:1)
您必须使用这样的构造函数。
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());
}
答案 1 :(得分:1)
由于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
类,您应该考虑使用LocalDate
或LocalDateTime
-这两个类都是不可变的。
答案 2 :(得分:1)
您需要返回内部(不可变)状态的副本。您不应该公开内部引用。
例如:
public final Date getDob() {
return new Date(dob.getTime());
}