Java面试问题之十八
阅读以下代码段,结合代码的意图分析此代码是否能够实现这个目的。
import java.util.Date;public final class Schedule { private final Date start; //开学时间,不允许被修改 private final Date end; //放假时间,不允许被修改 public Schedule(Date start,Date end){ if(start.compareTo(end)>0) throw new IllegalArgumentException(start+" after "+end); this.start=start; this.end=end; } public Date getStart(){ return start; } public Date getEnd() { return end; } }
import java.util.Date;public final class Schedule { private final Date start; private final Date end; public Schedule(Date start,Date end) { if(start.compareTo(end)>0) throw new IllegalArgumentException(start+" after "+end); this.start=new Date(start.getTime()); //采用保护性拷贝 this.end=new Date(end.getTime()); //采用保护性拷贝 } public Date getStart() { return (Date)start.clone(); //采用保护性拷贝 } public Date getEnd() { return (Date)end.clone(); //采用保护性拷贝 }}