Working with setters and getters
So far, we have been working with fields to encapsulate data in our instances. We could access the fields without any kind of restrictions as member variables for an instance. However, as it happens sometimes in real-world situations, restrictions are necessary to avoid serious problems. Sometimes, we want to restrict access or transform specific fields into read-only fields. We can combine the access restrictions to an underlying field with methods known as setters and getters.
Setters are methods that allow us to control how values are set; that is, these methods are used to change the values of related fields. Getters allow us to control the values that we return when we want to retrieve the value for a related field. Getters don't change the values of related fields.
Note
While some frameworks such as JavaBeans force you to work with setters and getters for each related field to be accessible, in other cases, setters and getters won't be necessary. In the...