Concept
Why are getters, setters, and immutable member variables useful?
ComputerScienceOne / Constructors
"Controlling access of member variables through getters and setters is good encapsulation. Doing so makes your code more predictable and more testable. Making your member variables public means that any piece of code can change their values. There is no way to do validation or prevent bad values. In fact, it is good practice to not even have setter methods. If the value of member variables cannot be changed, it makes the object immutable. Immutability is a nice property because it makes instances of the class thread-safe. That is, we can use instances of the class in a multithreaded program without having to worry about threads changing the values of the instance on one another."
Related Ideas
- What is a constructor and how is it written?ComputerScienceOne · Constructors
- How can constructors call one another and copy objects?ComputerScienceOne · Constructors
- How can getters and setters validate values and support immutable objects?ComputerScienceOne · Accessor & Mutator Methods
- How does Java handle default and multiple constructors?ComputerScienceOne · Constructors
- What section covers Usage?ComputerScienceOne · Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .