Getter and Setter are methods used to protect your data and make your code more secure. Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the convenience of the program, getter starts with the word “get” followed by the variable name.
While Setter sets or updates the value (mutators). It sets the value for any variable which is used in the programs of a class. and starts with the word “set” followed by the variable name. Getter and Setter make the programmer convenient in setting and getting the value for a particular data type. In both getter and setter, the first letter of the variable should be capital.
Example 1
// Java Program to Illustrate Getter and Setter
// Importing input output classes
import java.io.*;
// Class 1
// Helper class
class GetSet {
// Member variable of this class
private String name;
// Method 1 - Getter
public String getName() { return name; }
// Method 2 - Setter
public void setName(String N)
{
// This keyword refers to current instance itself
this.name = N;
}
}
// Class 2
// Main class
class OJC {
// Main driver method
public static void main(String[] args)
{
// Creating an object of class 1 in main() method
GetSet obj = new GetSet();
// Setting the name by calling setter method
obj.setName("Oracle Java Certified");
// Getting the name by calling geter method
System.out.println(obj.getName());
}
}
Output
Oracle Java Certified
Getter and Setter give you the convenience to enter the value of the variables of any data type as per accordance with 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 as in the program been discussed below as follows:
// Java Program to Illustrate Getter and Setter
// Importing input output classes
import java.io.*;
class GetSet {
// Member variable of this class
private int num;
// Method 1 - Setter
public void setNumber(int number)
{
// Checking if number if between 1 to 10 exclusive
if (number < 1 || number > 10) {
throw new IllegalArgumentException();
}
number = num;
}
// Method 2 - Getter
public int getNumber() { return num; }
}
// Class 2
// MAin class
class OJC {
// Main driver method
public static void main(String[] args)
{
GetSet obj = new GetSet();
// Calling method 1 inside main() method
obj.setNumber(5);
// Printing the number as setted above
System.out.println(obj.getNumber());
}
}
Output
0
Output explanation:
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.
Source: geeksforgeeks.org
0 comments:
Post a Comment