Accessors and Mutators in Java.

Java accessor and mutaotrs

Accessors and Mutators are two very important concepts in Java. It is used to read and update the private data member of a class. 

To understand this concept more clearly we first have to understand encapsulation and access specifiers. Encapsulation is an important concept in Object-oriented programming and it is implemented by wrapping up the data and methods into a single unit. 

The data present inside the class need to be secure and for this, we declare the data in a class as private. We cannot access the private data-member of other classes outside that class. To read and update the private data member a class outside that class we have to use public methods of that class. These methods are called Accessors or Getters and Mutators or Setters

Accessor or Getters are methods used to return the value of a private field of a class. It does not change the state of the Object. 

example:

public String getName() {
    return name; 
}    

Mutators or Setters are methods used to set a value of a private field of a class. It changes the state of the object. 

example:

public void setName(String fullName) {
    name = fullName;
}    


Example Java Program to Understand Accessors and Mutators.

public class Student {
    
    //attribute
    private int studId;
    private String studName;
    
    //Accessors or Getters
    public int getStudId() {
        return studId;
    }
    public String getStudName() {
        return studName;
    }
    //Mutators or Setters
    public void setStudId(int studId) {
        this.studId = studId;
    }
    public void setStudName(String studName) {
        this.studName = studName;
    }
}

import java.util.*;

public class Main
{
	public static void main(String[] args) {
	    //Object Creation
	    Student Obj = new Student();
	    
	    //assign value using Setters
	    Obj.setStudId(112);
	    Obj.setStudName("Rahul");
	    
	    //retrive value using Getters
	    System.out.println("Student ID: "+Obj.getStudId());
	    System.out.println("Student Name: "+Obj.getStudName());
	}
}
Output:
Student ID: 112
Student Name: Rahul

In the above example, we can see that how we are reading and updating the private data member of the Student class from the Main class with the help of the Object of Student class. 

Hope you found this article useful if you have any question related to this topic feel free to ask me in the comment section below. 

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS