Combining setters, getters, and a related property
Sometimes, we want to have more control over the values that are set to properties and retrieved from them, and we can take advantage of getters and setters to do so. In fact, we can combine a getter and a setter, which generate a computed property and a related property that stores the computed value, and access protection mechanisms to prevent the user from making changes to the related property and force him to always use the computed property.
The superhero's sneakers might change over time. However, we always have to make sure that the sneakers' name is an uppercase string. We can define a sneakers
property with a getter method that always converts the string value to an uppercase string and stores it in a private sneakersField
property.
Whenever we assign a value to the sneakers
property, the setter method is called under the hood with the value to be assigned as an argument. Whenever we specify the sneakers
property in any expression...