Using Accessors and Mutators in Java
What is Accessors ?
- The methods that retrieve the data of fields are called accessors.
- The data can be accessed but not changed.
- The name of an accessor method starts with the word get.
Syntax
What is Mutators ?
- The methods that modify the data of fields are called mutators.
- The name of a mutator method starts with the word set.
Syntax
Accessors and Mutators
- We can enforce data encapsulation is through the use of accessors and mutators.
- The role of accessors and mutators are to return and set the values of an object's state.
Accessor Methods
- An accessor method is used to return the value of a private field. It follows a naming scheme prefixing the word "get" to the start of the method name.
- For example let's add accessor methods for firstname, middleNames and lastname:
- These methods always return the same data type as their corresponding private field (e.g., String) and then simply return the value of that private field.
- We can now access their values through the methods of a Person object:
Mutator Methods
- A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word "set" to the start of the method name. For example, let's add mutator fields for address and username:
- These methods do not have a return type and accept a parameter that is the same data type as their corresponding private field. The parameter is then used to set the value of that private field.
- It's now possible to modify the values for the address and username inside the Person object:
Why Use Accessors and Mutators ?
- We could just change the private fields of the class definition to be public and achieve the same results. It's important to remember that we want to hide the data of the object as much as possible. The extra buffer provided by these methods allows us to:
- We decide to modify how we store middle names. Instead of just one String we now use an array of Strings.
- Change how the data is handled behind the scenes
- Impose validation on the values that the fields are being set to.
- The implementation inside the object has changed but the outside world is not affected. The way the methods are called remains exactly the same.
- Or, let's say the application that is using the Person object can only accept usernames that have a maximum of ten characters. We can add validation in the setUsername mutator to make sure the username conforms to this requirement:
- change how the data is handled behind the scenes
- impose validation on the values that the fields are being set to.
- Now if the username passed to the setUsername mutator is longer than ten characters it is automatically truncated.