1.问题
/**
* 输出: Mon Apr 26 10:54:10 CST 2010
* Mon Apr 26 10:54:10 CST 2010
*/
public static void main(String[] args){
Example test = new Example(new Date());
Date d = test.getDate();
double tenYearsInMillisSeconds = 10 * 365.25 * 24 * 3600 * 1000;
d.setTime((long) (d.getTime() - tenYearsInMillisSeconds));
System.out.println(d);
System.out.println(test.getDate());
}
public class Example {
private Date date;
public Example(Date date){
this.date = date;
}
public Date getDate() {
return date;
}
}
Date类破坏了Example的封装,导致修改实例 d时影响了 test 的值,原因是Date类生成的对象是可变的。
2.对象与对象变量
Date birthday = new Date();
Date deadline = birthday;
这两个变量引用同一个对象(请参见图 4-4 )。