This is an example of defensive copy in Effective java. Assume that scenario's in my underlying questions need a defensive copy, and cannot do with a comment asking client to avoid mutating objects passed in.
public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
}
Questions:
What to do if
Date
did not have a constructor to take itself in, to make my self more general, an object is passed with no mechanism to replicate itself, and such object does not belong to us, ie we cant change it in any way ?What if the constructor took type parameter as an argument, say
Period(T object)
and T could be mutable so needs defensive copy. We dont have any idea of what is T. How to do defensive copy in this case ?What is an interface is passed where some of its subclasses do have a constructor like
Date
to create an object of itself and some of its subclasses dont have any mechanism to do so ?How deep should we defensively copy ? Lets say we copy an array, but array elements were mutable ?