×

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

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.