请先看一个案例:12345678910111213141516/** * 职员类 * * @author xianxiaotao */public class Employee { private Date hireDay; public Employee(Date hireDay) { this.hireDay = hireDay; } public Date getHireDay() { return this.hireDay; // bad coding }}
职员,受雇日期是固定不变的,即使将属性设置为私有,依然可以使用这段代码直接将职员工龄增加10年:1234Employee harry = new Employee(new Date());Date d = harry.getHireDay();double tenYearsInMilliSeconds = 10 * 365.25 * 24 * 60 * 60 * 1000;d.setTime(d.getTime() - (long) tenYearsInMilliSeconds);
如果需要返回一个可变对象的引用,应该首先对它进行克隆(clone),代码修改如下:123public Date getHireDay() { return (Date) hireDay.clone();// Ok}
建议使用LocalDate代替Date