Java setting private fields inside constructors

前端 未结 10 654
独厮守ぢ
独厮守ぢ 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 15:56

    Initializing variables inside constructor is a very common practice. It can be used to assign values to variables based on which constructor user has called. You cannot write code based on assumption that the client code will invoke setter method to assign value to instance variables. It is always safe to assign default value to a variable when its object is created (i.e inside constructor).

    There is a difference between initializing variables within constructor and setting it to different value as per requirement of the calling code(using setter method). Both have different purposes and different objectives.

提交回复
热议问题