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

前端 未结 3 1657
温柔的废话
温柔的废话 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: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.

提交回复
热议问题