I\'m adding an instance variable to a class \"Person\" which is a reference type (\"Date\", which I have written a class for). In the constructor for my Person class, I am there
You can just simple
this.birthday = (Date) birthday.clone();
Why this way instead of ?
this.birthday = birthday;
Cause outsiders can modify your date object, and then they are modifying your internal structure and that is not good, breaks encapsulation.
Why this way instead of ?
this.birthday = new Date(birthday.getTime())
;
Date is not a final class what happen if Date object
you pass is not a "true Date" and is a subclass , if you do this don't preserve internal structure of subclass, but when you cloning preserves the information, but this approach it depends on what you want.