Accessor and Mutator methods in Java
Accessor and Mutator methods in Java
In this post, we will learn about the Accessor and Mutator methods in Java. These methods are used to retrieve and set the instance variables of a class. The methods are also called Getters and Setters respectively.
Build methods for each private data variable. We need to declare public methods to operate on our private data.
One method to get the value of the private data item -> Getter or Accessor or Get method
One method to set the value of the private data item -> Setter or Mutator or Set method
Example
Let’s take the Product class as an example and generate methods for the class. The product class has three instance variables name, price, and quantity.
public class Product { private String name; private double price; private int quantity; }
Accessor method
We use the Accessor method to get the value stored in the private instance variable of the class. This method is also called the Getter method. This method returns the variable value.
Example:
/**
* @return the name
*/
public String getName() {
return name;
}
Usage:
Product p = new Product();
String productName;
productName= p.getName(); //to get the product name in the p object.
Mutator method
We use the Mutator method to store or change the value of the instance variable of the class. This method is also called the Setter method. This method sets the variable value.
Example:
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
Usage:
Product p = new Product();
p.setName("Phone"); // to set the product name in the p object.
Create Accessor and Mutator methods
IDEs like Eclipse, IntelliJ, etc. will allow creating the methods automatically for you.
Implement getters and setters for instance variables/attributes of your Java class. The Eclipse IDE will automatically create them for you with the option:
Right-click >> Source >> Generate Getters and Setters.
Check the variables for which you want to create the methods. You can do a Select All to create the methods for all the variables in the class.
Check the Generate method comments to generate comments for the methods.
Click the OK button.
You will find the methods and comments created.
Code Listing
//Product class public class Product { private String name; private double price; private int quantity; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the price */ public double getPrice() { return price; } /** * @param price the price to set */ public void setPrice(double price) { this.price = price; } /** * @return the quantity */ public int getQuantity() { return quantity; } /** * @param quantity the quantity to set */ public void setQuantity(int quantity) { this.quantity = quantity; } }