In Java, Getter and Setter are methods used to protect your data and make your code more secure. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type.
Getter in Java: Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program’s convenience, the getter starts with the word “get” followed by the variable name.
Setter in Java: While Setter sets or updates the value (mutators). It sets the value for any variable used in a class’s programs. and starts with the word “set” followed by the variable name.
Syntax
class ABC{
private variable;
public void setVariable(int x){
this.variable=x;
}
public int getVariable{
return variable;
}
}
Note: In both getter and setter, the first letter of the variable should be capital.
Examples of Getter and Setter in Java
Example 1:
Java
import java.io.*;
class GetSet {
private String name;
public String getName() { return name; }
public void setName(String N)
{
this .name = N;
}
}
class GFG {
public static void main(String[] args)
{
GetSet obj = new GetSet();
obj.setName( "Geeks for Geeks" );
System.out.println(obj.getName());
}
}
|
Getter and Setter give you the convenience of entering the value of the variables of any data type by the requirement of the code. Getters and setters let you manage how crucial variables in your code are accessed and altered. It can be seen in the program discussed below as follows:
Example 2
Java
import java.io.*;
class GetSet {
private int num;
public void setNumber( int number)
{
if (number < 1 || number > 10 ) {
throw new IllegalArgumentException();
}
num = number;
}
public int getNumber() { return num; }
}
class GFG {
public static void main(String[] args)
{
GetSet obj = new GetSet();
obj.setNumber( 5 );
System.out.println(obj.getNumber());
}
}
|
Explanation of the above program:
Here we can see that if we take a value greater than 10 then it shows an error, By using the setNumber() method, one can be sure the value of a number is always between 1 and 10. This is much better than updating the number variable directly.
Note: This could be avoided by making the number a private variable and utilizing the setNumber method. Using a getter method, on the other hand, is the sole way to read a number’s value.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 Jun, 2023
Like Article
Save Article