×

Accessors and Mutator in Java

Introduction

Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The necessity for getter and setter methods arises because if we had designated the variables as private, only we would have access to them.

External clients should be able to utilize our classes, and create procedures for every private data element. In order to work on our private data, we must declare public methods.

Some well-known IDEs, like Netbeans, Eclipse, IntelliJ, and others, automatically build accessor and mutator methods. Let’s discuss them in detail.

Accessor

The Accessor method returns one of the object's properties. These are acknowledged as public and are accessible easily. Accessors adhere to a naming convention; in other words or terms, they append a word to the procedure name's beginning. Common terms for an accessor method include "get method" and "getter." These are employed in order to retrieve the values of a private field. Depending on their private field, these methods return the same data type.

The word "access," which enables the user to access the secret data in a class, serves as the inspiration for the name of the accessor function.

Accessors are the same as "getters," the "get" method, and other similar terms. The private constants and variables are retrieved by the getters so that they can be used outside of a class.

It is customary to write the accessor solution's name in the get word first. So that they may be seen in the class at easy accessor method, declarations must be public. However, accessor methods don't take any arguments. But they give the value of a private variable back. As a result, it calls the function and returns the value from the private variable. In order to return private variables, we typically need to write many accessor methods in the class, each with a unique name.

Syntax used for accessor:

In programming languages like Java, accessors are denoted by the term "get." We can use the getter getName()  to get the variable  "name". Take a look at the example of the accessor method below.

Syntax:

public String getmethodname ()
{
return value;
}

Another Syntax:

public int getValue()
{
return Value;
}

Example:

public class Employee
{
private String data;
public String getName()
{
return data;
}
} 

Note: Please note that each getter contains the term "get" in the method Employee information data before the variable name, and the return type matches the type of the variable being returned. The getter/accessor method also returns a "String" because the variable "data" is of the "String" type.

Example for accessor method 1:

public class Student 
{  
    private int name;  
    public int getName() 
    {  
        return name;  
    }  
    public void setName(int newName) 
    {  
        name = newName;  
    }  
}    

Example 2:

//a program illustrating th java accessor method "getter" method
public class Employee 
{
    // variables of student class using the private 
    private int eid;
    private String ename;


    // using the constructors
    Employee(int e, String en) 
    {
        this.eid = e;
        this.ename = en;
    }


    // to get the eid and ename using the accessor method
    public int getEid() 
    {
        return eid;
    }
    public String getEname() {
        return ename;
    }


    // the main method of the java programming language 
    public static void main(String s[]) 
    {
        Employee emp = new Employee(15, "chandu varada");


        // the calling method for accessor method 
        System.out.println("Employee id  - " + emp.getEid());
        System.out.println("Employee Name  - " + emp.getEname());
    }
} 

Output:

Employee id  - 15
Employee Name  - chandu varada

Mutator

A procedure called a "mutator" modifies or "mutates" something.

It demonstrates the idea of encapsulation. A set method, often known as a setter, is another name for a Mutator method. They go by the name of modifiers as well. These are simple to identify because they begin with the word set. They have been deemed public. In accordance with their private field, mutator methods either accept a parameter of the same data type or do not have a return type at all. The value of the private field is then set using it.

We use the Mutator method to modify an object's characteristics in Java. In other words, the Mutator method sets the initial value of a class's instance variable or a private class variable. We can therefore conclude that encapsulation is provided via the mutator approach.

Generally, the set word is written at the start of the mutator method's name; to make sure they stand out in the class. Public methods for mutators must be declared. However, there is no return type for Mutator methods. But based on the type of the private variable, they may accept a parameter. Then, it will use the keyword this to access the private variable and set its value to the parameter's value. In the class, we can create multiple mutator methods with unique names.

Since private data members cannot be directly updated, setters help with encapsulation. The value of a variable can therefore be changed outside the scope of a class using setter methods or mutators.

The class instance variable's value is stored or modified using the Mutator method.

The syntax for the Mutator method:

public void set Size(int Size) 
{  
    this.Size = Size;  
}  

Syntax 2:

public void setmethodname(element1, element2, ...) 
{
   //private variables of the elements are going to be set in this method
}

Syntax 3:

public class Employee 
{
private String phno;
public void setPhno(String phno)
 {
this.phno = phno;
}
}

Example for mutator method:

import java.util.*;
//a program demonstrating the mutator method
public class Employee
{
    // private variables of an employee class are to be declared
    private int eid;
    private String ename;


    // the multiple and many details of the mutator method to be set by using this method
    public void setDetails(int e, String en) {
        System.out.println("Setter method inside");
        // to access the class variables, we have to use this method
        this.eid = e;
        this.ename = en;
    }
    public static void main(String s[]) 
    {
        Employee emp = new Employee();
        // we have to call the mutator method in the main method
        emp.setDetails(15, "chandu varada");
    }
}

Output:

Setter method inside

Examples for both accessor and mutator methods:

import java.util.*;


public class Studentinfo 
{
    private String sname;
private Integer sid;
private String dob;
private double cgpa;
private String[] coursesinfo;
    public String getSname() 
{
return sname;
}
    public void setSname(String sname) {
this.sname = sname;
}
    public Integer getsid() 
    {
return sid;
}
public void setsid(Integer sid) 
{
this.sid = sid;
}
public String getdob() 
{
return dob;
}
public void setdob(String dob) 
{
this.dob = dob;
}


public double getcgpa() 
{
return cgpa;
}
public void setcgpa(double cgpa) 
{
this.cgpa = cgpa;
}
    public String[] getcoursesinfo() 
    {
return coursesinfo;
}
public void setcoursesinfo(String[] coursesinfo) 
{
this.coursesinfo = coursesinfo;
}
public static void main(String[] args) 
{


Studentinfo st = new Studentinfo();
        System.out.println("Student information before accessor and mutator methods are applied");
        // we have to call the accessor method
System.out.println("STUDENT NAME: " + st.getSname());
System.out.println("STUDENT ID: " + st.getsid());
System.out.println("STUDENT CGPA: " + st.getcgpa());
System.out.println("STUDENT DOB: " + st.getdob());
System.out.println("STUDENT COURSES: " +  Arrays.toString(st.getcoursesinfo()));


// we have to call mutator method
st.setSname("chandu varada");
st.setsid(20251);
st.setcgpa(9.12);
st.setdob("16/02/2003");
String[] coursesinfo = { "oops through java", "Data structures", "database management system", "cyber Security" };
st.setcoursesinfo(coursesinfo);


System.out.println("Student information after accessor and mutator methods are applied");


// we have to call the accessor method
System.out.println("STUDENT NAME: " + st.getSname());
System.out.println("STUDENT ID: " + st.getsid());
System.out.println("STUDENT CGPA: " + st.getcgpa());
System.out.println("STUDENT DOB: " + st.getdob());
System.out.println("STUDENT COURSES: " +  Arrays.toString(st.getcoursesinfo()));
}
}

Output:

Student information before accessor and mutator methods are applied
STUDENT NAME: null
STUDENT ID: null
STUDENT CGPA: 0.0STUDENT DOB: null
STUDENT COURSES: null
Student information after accessor and mutator methods are appliedSTUDENT NAME: chandu varada
STUDENT ID: 20251
STUDENT CGPA: 9.12STUDENT DOB: 16/02/2003
STUDENT COURSES: [oops through Java, Data structures, database management system, cyber Security]

Difference between Accessor and Mutator

  • The accessor method will return a value, whereas the mutator method will not return any values.
  • The getPriority() method can be used by the accessor method, whereas the setPriority() method can be used by the mutator method.
  • The Java.lang package's Thread class contains this method in both the setter and getter methods.
  • We give the thread name in a setter and get it back in a getter.

Conclusion

The main aim of the accessor and mutator are:

These techniques stop unauthorized access to these items, whether purposeful or accidental.

Our major goal is to conceal the data of the object as much as we can. These techniques also enforce validation on the values that are being set.


Related Topics

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.