Java setting private fields inside constructors

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

    Depending on the context, the use of getters and setters is actually a bigger violation of encapsulation than using member variables in constructors. If you want to set the member variable 'name' of this class, either of these approaches would work since the construction is hidden from the caller and thus not violating encapsulation. One warning is that the use of setName within the constructor might call an overrided method in a subclass which may not be what you want (since it may leave name undefined in the superclass).

    Here's a similar question to yours that may provide additional insight:

    calling setters from a constructor

提交回复
热议问题