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

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

提交回复
热议问题