Consider the example in Bloch's Item 50 (3rd Edition):
// Broken “immutable” time period class
public final class Period { // Question 3
private final Date start;
private final Date end;
/**
* @param start the beginning of the period
* @param end the end of the period; must not precede start
* @throws IAE if start is after end
* @throws NPE if start or end null
*/
public Period (Date start, Date end) {
if (start.compareTo(end) > 0) throw new IAE();
this.start = start; this.end = end; // Question 1
}
public Date start() { return start;} // Question 2
public Date end() { return end;} // Question 2
}
// Question 1
.
// Question 2
.
public class Period { // Question 3
Write code that shows the problem.
public Period (Date start, Date end) {
this.start = new Date(start.getTime()); // Defensive copy
this.end = new Date(end.getTime()); // Defensive copy
if (this.start.compareTo(end) > 0) throw new IAE();
clone()
would be inappropriate for copying
the dates.
Write code that shows the problem.