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
Are you saying you want to initialize this.birthday
in the constructor of Person using the Date constructor? Then use the new
keyword like this:
this.birthday = new Date(<arguments if any exist>);
new
calls the constructor of an object. If that's the case, you do not need the Date birthday
constructor argument for Person, unless you use it for something else.
You can do this:
this.birthday = new Date(birthday.getTime());
This creates a copy of the date object. Since a Date can be modified it is dangerous to use the same object, which you'd be doing if you just copied the reference:
this.birthday = birthday;
That would allow the outside world to change your birthday without you knowing about it.
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.