Combining setters, getters, and fields
Sometimes, we want to have more control over the values that are set to related fields and retrieved from them, and we can take advantage of getters and setters to do so. We can combine a getter, a setter, a related field that stores a computed value, and the access protection mechanisms to prevent the user from making changes to the related field. This way, we will force the user to always use the getters and setters.
Virtual creatures love any kind of hat. The hat for a virtual creature can change over time. We have to make sure that the hat's name is in capital letters, that is, an uppercased String
. We will define a setHat
method that always generates an uppercased String
from the received String
and stores it in a private hat
field.
We will provide a getHat
method to retrieve the value stored in the private hat
field. The following lines show a new version of the VirtualCreature
class that adds a hat
private instance field and the getHat
and...