Java setting private fields inside constructors

前端 未结 10 774
独厮守ぢ
独厮守ぢ 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:09

    Its ok to directly assign values with in class provided setter doesn't do any other processing.

    Basically setters/getters are used to provide restrictive access to private data such as returning copy of the data instead of reference of private object, validating data in getter etc..

    Since the constructor is part of the object itself, and we are sure what we are doing is right, then its ok.

提交回复
热议问题