Accessor and Mutator Methods in Java [Practical Examples]

Accessor and Mutator in Java - Introduction

In java, public methods that are used to get and set the value of the private variable are refereed as a Accessor and Mutator respectively. They are also referred as a getter and setter method respectively. Some popular IDE's like Netbeans, Eclipse, IntelliJ etc. creates accessor and mutator method automatically.

 

Accessor Method in Java

In java, Accessor method are used to access the property of an object. In other words, Accessor method act as a mediator to access the private variable by methods outside a class or some other class. Hence, we can say that accessor method is used to provide encapsulation. The Accessor method is also known as a getter method.

Advertisement

It is a general convention to write the accessor methods name beginning with the get word. So that they are easily spotted in the class. Accessor method must be declared as public methods. Although, Accessor methods do not accept any parameters. But, they return a value of a private variable. Therefore, it access the private variable and return that from the function. Generally, We have to write more than one accessor method with different names in the class to return private variables.

The statement below shows the syntax of Accessor method in Java.

public returntype getmethodname() {
    return value;
}

Example 1:In this example, we will initialize the private variable sid and name using constructor and then using getter method to retrieve the values. As, a method can return only one value at a time, we have to write multiple accessors to retrieve the values of private variables.

// Program to demonstrate Accessor in java
public class Student {
    // private class variable
    private int sid;
    private String name;

    // constructor
    Student(int s, String n) {
        this.sid = s;
        this.name = n;
    }

    // Accessor method to get sid and name
    public int getSid() {
        return sid;
    }
    public String getName() {
        return name;
    }

    // Main method
    public static void main(String s[]) {
        Student st = new Student(12, "john");

        // Calling accessor method
        System.out.println("Student id  - " + st.getSid());
        System.out.println("Student Name  - " + st.getName());
    }
} 

Output

Student id  - 12
Student Name  - john

 

Mutator Method in Java

In java, Mutator method are used to change the properties of an object. In other words, Mutator method initialize or change the value of the instance variable of the class or a private variable of the class. Hence, we can say that mutator method is used to provide encapsulation. A Mutator method is also known as a Setter method or Modifiers.

It is a general convention to write the mutator methods name beginning with the set word. So that they are easily spotted in the class. Mutator method must be declared as public methods. Although, Mutator methods do not have any return type. But, they can accept a parameter depending on the data type of private variable. Thereafter, it will access the private variable using keyword this and set its value as received in the parameter. We can write more than one mutator method with different names in the class.
The statement below shows the syntax of Accessor method in Java.

Advertisement
public void setmethodname(parameter1, parameter2, ...) {
    // sets the value of private variables from the parameters
}

Example 1:

// Program to demonstrate mutator in java
public class Student {
    // Declaring private class variable
    private int sid;
    private String name;

    // Mutator method to set multiple details
    public void setDetails(int s, String n) {
        System.out.println("Inside setter method");
        // Accessing class variable using this keyword
        this.sid = s;
        this.name = n;
    }

    // Main method
    public static void main(String s[]) {
        Student st = new Student();
        // Calling mutator method
        st.setDetails(12, "John");
    }
}

Output

Inside setter method

 

Accessor and Mutator Examples

Example 1: Accessor and Mutator methods in Student class

In this example, we are using both accessor and mutator to get and set the personal details of a student. We can use mutator method to restrict storing some invalid data. Here in the example, we will throw an IllegalArgumentException if the length of name is less than 3 characters. Similarly, we can write an appropriate conditions to restrict the type of values stored in the variable.

// Program to demonstrate the accessor and mutator in java
public class student {
    // Declaring Class variables
    private int sid;
    private String name;
    private long contact;

    // Accessor methods
    public int getSid() {
        return sid;
    }
    public String getName() {
        return name;
    }
    public long getContact() {
        return contact;
    }

    // Mutator methods
    public void setDetails(int s, String n, long c) {
        if (n.length() & lt; 3) throw new IllegalArgumentException("Name should be greater than 3 chars long");
        else
            this.name = n;

        this.sid = s;
        this.contact = c;
    }

    // Main
    public static void main(String s[]) {
        student st = new student();
        student st1 = new student();
        st.setDetails(11, "John", 234998723);
        System.out.println("Student id  - " + st.getSid());
        System.out.println("Student Name  - " + st.getName());
        System.out.println("Student Contactno  - " + st.getContact());

        st1.setDetails(12, "qq", 987655678);
        System.out.println("Student id  - " + st1.getSid());
        System.out.println("Student Name  - " + st1.getName());
        System.out.println("Student Contactno  - " + st1.getContact());
    }
}

Output

Student id  - 11
Student Name  - John
Student Contactno  - 234998723
Exception in thread "main" java.lang.IllegalArgumentException: Name should be greater than 3 chars long
	at student.setDetails(student.java:24)
	at student.main(student.java:38)

 

Example 2: Accessor and Mutator methods in Bank Class

In this example, we are using both accessor and mutator to get and set the personal details of a customer in a bank. We can use mutator method to restrict storing some invalid data. Here in the example, we will keep minimum deposit amount as 1000. So, we will throw an IllegalArgumentException if the amount is less than 1000. Similarly, we can write an appropriate conditions to restrict the type of values stored in the variable.

// Program to demonstrate the accessor and mutator in java
public class Bank {
    // Declaring Class variables
    private long accno;
    private String name;
    private String acctype;
    private double amount;

    // Accessor methods
    public long getAccno() {
        return accno;
    }
    public String[] getDetails() {
        String temp[] = {
            name,
            acctype
        };
        return temp;
    }
    public double getAmount() {
        return amount;
    }

    // Mutator methods
    public void setDetails(long a, String n, String t, double c) {
        this.accno = a;
        this.acctype = t;
        if (n.length() & lt; 3) throw new IllegalArgumentException("Name should be greater than 3 chars long");
        else
            this.name = n;

        if (c & lt; 1000) throw new IllegalArgumentException("Minimum Deposit 1000 required");
        else
            this.amount = c;

    }

    // Main
    public static void main(String s[]) {
        Bank b1 = new Bank();
        Bank b2 = new Bank();
        b1.setDetails(11335566, "John", "Savings", 1000);
        System.out.println("Customer Account no  - " + b1.getAccno());
        String temp[] = b1.getDetails();
        System.out.println("Custormer Name - " + temp[0]);
        System.out.println("Custormer Account Type - " + temp[1]);
        System.out.println("Customer Balance  - " + b1.getAmount());

        b2.setDetails(12223344, "Kim", "Current", 750);
        System.out.println("Customer Account no  - " + b2.getAccno());
        temp = b2.getDetails();
        System.out.println("Custormer Name - " + temp[0]);
        System.out.println("Custormer Account Type - " + temp[1]);
        System.out.println("Customer Balance  - " + b2.getAmount());
    }
}

Output

Advertisement
Customer Account no  - 11335566
Custormer Name - John
Custormer Account Type - Savings
Customer Balance  - 1000.0
Exception in thread "main" java.lang.IllegalArgumentException: Minimum Deposit 1000 required
	at Bank.setDetails(Bank.java:29)
	at Bank.main(Bank.java:47)

 

Summary

The knowledge of Accessor and Mutator is very useful as it implements encapsulation, which is one of the important feature of Object oriented Programming. When we want our class to be used by external clients or external classes, we can build methods for each private data variable using accessor and mutator. Thereafter, we will need to declare public methods to operate on private data. In this tutorial, we covered the way to create accessor and mutator methods in Java with example. All in all, this tutorial, covers everything that you need to know in order to understand the Accessor and Mutator methods in Java.

 

References

Accessor
Mutator
Accessor and Mutator Methods

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X