Java的Getter 和 Setter
Getter 和 Setter 是用于保护您的数据并使您的代码更安全的方法。 getter 返回值(访问器),它返回数据类型为 int、String、double、float 等的值。为了程序的方便,getter 以“get”一词开头,后跟变量名。
而 Setter 设置或更新值(mutators)。它为类的程序中使用的任何变量设置值。并以单词“set”开头,后跟变量名称。 Getter 和 Setter 使程序员可以方便地设置和获取特定数据类型的值。在 getter 和 setter 中,变量的第一个字母应该是大写的。
示例 1
Java
// 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 GFG {
// 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("Geeks for Geeks");
// Getting the name by calling geter method
System.out.println(obj.getName());
}
}
Java
// 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 GFG {
// 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());
}
}
Geeks for Geeks
Getter 和 Setter 使您可以方便地根据代码的要求输入任何数据类型的变量的值。 Getter 和 setter 可让您管理代码中关键变量的访问和更改方式。可以看出,在程序中讨论如下:
示例 2
Java
// 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 GFG {
// 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());
}
}
0
输出说明:
在这里我们可以看到,如果我们取一个大于 10 的值,那么它会显示一个错误,通过使用 setNumber() 方法,可以确定一个数字的值总是在 1 到 10 之间。这比更新数字变量直接。
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.