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
- How can getters and setters validate values and support immutable objects?ComputerScienceOne · Accessor & Mutator Methods
- How can getters and setters validate values before changing private variables?ComputerScienceOne · Accessor & Mutator Methods
- How do accessor and mutator methods provide access to private member variables?ComputerScienceOne · Accessor & Mutator Methods
- How do accessor and mutator methods use this to access instance variables?ComputerScienceOne · Accessor & Mutator Methods
- What are the visibility levels used to protect Java data?ComputerScienceOne · Data Visibility
- What does the completed Java Student class example contain?ComputerScienceOne · Example
- How can adding an addCourse method make a Student object more flexible?ComputerScienceOne · Example
- How should a class manage owned collections and avoid shallow copies?ComputerScienceOne · Composition