Java setting private fields inside constructors

前端 未结 10 649
独厮守ぢ
独厮守ぢ 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.

    0 讨论(0)
  • 2021-01-17 16:10

    My preferred approach (as described by Joshua Bloch in "Effective Java") is to make the constructor private, make the fields final (i.e., eliminate the setters entirely), and require clients to obtain instances either using the Builder Pattern or Factory Method Pattern, which would take care of any necessary validation to protect invariants. Then the (private) constructor would simply directly assign the given parameters (which have already been validated by the Builder or Factory Method) to the appropriate fields, which are private and final.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-17 16:12

    Setting variables to private is to encourage encapsulation from other classes.

    Unless setName(String) was meant to do something extra (which the method name doesn't imply), it's unnecessary to use the setter while you're in the class where the private variable is.

    0 讨论(0)
提交回复
热议问题