Java setting private fields inside constructors

前端 未结 10 665
独厮守ぢ
独厮守ぢ 2021-01-17 15:48

Common design practice is to make instance variables private and have public getters and setters to access them. But many times I have seen code samples on the internet that

10条回答
  •  鱼传尺愫
    2021-01-17 16:08

    This does not defeat encapsulation since the private member is still hidden from the other classes

    If the modifier method does not contain any logic and just sets the member then there is no difference between directly setting the member of calling its setter method although for better practice the setter should be called.

    The setter indicates that this person's name might change in the future and allows it easily without creating an entire person object again.

提交回复
热议问题