Posted by Marta on December 4, 2021 Viewed 29446 times
In this article, you will learn what a mutator method in java and accessor method. Additionally, you will understand the benefits of using mutator and accessor methods and see some java examples.
The mutator and accessor method concepts are closely related to object-oriented programming and encapsulation. In case you are not familiar with object-oriented programming. I have included a brief introduction below; however, if you would like further details, check out the documentation.
Object Oriented Programming means that you solve problems representing the entities of the problem as classes. A class has a state and methods where the state is a set of variables containing the relevant data in our representation. And the methods determine the operations our class can perform.
For example, we can define the class Circle:
public class Circle { private float radius; public Circle(float newRadius) { this.radius = newRadius; } public double area(){ return Math.PI * Math.pow(radius, 2); } }
This class is representing the circle concept. The circle class state has the radius and a method named area()
, which returns the circle area.
You can add the following code to the Circle
class to test it out:
public static void main(String[] args){ Circle circle1 = new Circle(3); System.out.println(circle1.area()); }
Output:
28.274333882308138
We have defined a class using object-oriented programming and created the object circle1
of the class Circle
. What if I wanted to modify the radius of the object circle1
. As the code stands, I can’t change it since there no method to access the radius
variable. All I can do is creating a new Circle object with a different radius. What can I do to correct this?
You can do two things; one will lead to a well-designed class, and the other to a poor, challenging to maintain design. One option is declaring the radius
field as a public field, so it is accessible outside the class. See the changes below:
public class Circle { public float radius; public Circle(float newRadius) { this.radius = newRadius; } public double area(){ return Math.PI * Math.pow(radius, 2); } public static void main(String[] args){ Circle circle1 = new Circle(3); System.out.println(circle1.radius); circle1.radius = 5; System.out.println(circle1.radius); } }
Output:
3.0 5.0
The other option is creating methods to access and modify the radius field, which allows you to hide the implementation details. This mechanism is also known as encapsulation.
The mutator method in java, and any object-oriented programming language, is a method that enables you to change the variables inside the class. Private is the access-level for the variables, meaning the only way to change the variables is by using the mutator methods. This way, the mutator methods can control the validity and quality of the data saved in the class.
For example, in the previous code snippet, the setRadius()
method is a mutator method. You could modify this method to add some data validation. For instance, an example of data validation could be checking if the new radius is a negative number.
Accessor methods are methods that allow reading the class fields to other methods or classes outside the class. This way enables you to control how the client code can access the class fields.
Let’s see some examples to illustrate the mutator and accessor methods. Setters and getters is another way of referring to accessor and mutator methods.
Below there is an example of how to add getters to a class. The class is called Product
, and it has two getters: getPrice()
and getName()
. These methods allow any client code to access the class variable, which is price
and name
.
import java.math.BigDecimal; public class Product { private BigDecimal price; private String name; // getter or accessor methods public BigDecimal getPrice() { return price; } public String getName() { return name; } }
And now, I will add the mutators, so I can access and modify the class variable.
import java.math.BigDecimal; public class Product { private BigDecimal price; private String name; public BigDecimal getPrice() { return price; } public String getName() { return name; } // mutator or setter methods public void setPrice(BigDecimal price) { if(price.compareTo(BigDecimal.ZERO)<0 )throw new IllegalArgumentException("Empty product name"); this.price = price; } public void setName(String name) { if(name.isEmpty()) throw new IllegalArgumentException("Empty product name"); this.name = name; } }
As you can see above, the setter methods setPrice()
and setName()
also include validation, making sure the data passed meet some criteria. For example, one of the requirements is that a price should always be above zero. In case the parameter is not valid, the code will throw an exception. Otherwise, it will assign the new value.
In java, the names of these methods, accessors, and mutators should follow specific naming conventions. These rules are entirely stabilized, which makes them essential to follow. Not following these conventions can create frustration and confusion when other people are reading your code.
Let’s start with the naming conventions for mutators. The method should be declared as public and return void. Moreover, the method name should begin with the word set
in lowercase. Followed by the class variable name with an initial capital letter. For instance, if our class has a variable called age
, then the mutator method should look as follows:
public void setAge(int age){...}
Along with mutators, we have seen the accessors, which also follow a similar naming convention. The rules are that the method should be declared as public. Additionally, the method name should start by get
, followed by the class variable name with an initial capital letter. The method has no parameters and returns the instance variable type. Following the previous example, let’s create an accessor method for the age
variable:
public int getAge(){...}
So far, we have seen the accessor and mutator methods in java with some examples. And familiarize ourselves with the naming conventions that you should follow when declaring these methods. However, how are these methods useful? The main benefit is encapsulation. This basically means that by creating these methods, you are hiding the internal details of your class from other components. Other components can only communicate via the API.
Consequently, classes are decoupled; they don’t depend on each, allowing you to develop in isolation, which leads to faster developments since team members can create different classes and components in parallel. Besides easing maintenance, since components can be modified, with a small impact on other dependant components.
To summarise, in this article, we have seen that mutator methods and accessors methods in java are methods that enable us to read and write class variables. Their primary purpose is helping us to design classes that are well encapsulated and decoupled from each other.
I hope you find the article useful, and thank you so much for reading and supporting this blog! Happy coding!
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java