How to initialize a reference attribute in a constructor in Java?

前端 未结 3 1658
温柔的废话
温柔的废话 2021-01-27 11:52

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

相关标签:
3条回答
  • 2021-01-27 12:18

    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.

    0 讨论(0)
  • 2021-01-27 12:22

    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.

    0 讨论(0)
  • 2021-01-27 12:23

    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.

    0 讨论(0)
提交回复
热议问题